The math/big package in Go provides arbitrary-precision decimal arithmetic. It includes types such as Rat and Float, which can be used to perform calculations with a high degree of precision.
Example 1: Using the big.Rat type
package main
import ( "fmt" "math/big" )
func main() { rat := big.NewRat(10, 3)
// Print the rational number as a decimal fmt.Println(rat.FloatString(2))
// Multiply by 2 and print the result two := big.NewRat(2, 1) rat.Mul(rat, two) fmt.Println(rat.FloatString(2)) }
Output: 3.33 6.67
In this example, we create a Rat type with the value 10/3. We then print the value as a decimal using the FloatString method. After that, we create a second Rat type with the value 2/1 and multiply the first Rat by it. We print the result again, which is now 20/3 (or 6.67 as a decimal).
Example 2: Using the big.Float type
The big.Float type allows us to perform arithmetic with arbitrary precision floating-point numbers.
package main
import ( "fmt" "math/big" )
func main() { f := big.NewFloat(1.23)
// Set the precision to 10 decimal places f.Prec = 10
// Multiply by 2 and print the result two := big.NewFloat(2) f.Mul(f, two) fmt.Println(f.String()) }
Output: 2.460000038
In this example, we create a big.Float type with the value 1.23. We then set the precision to 10 decimal places and multiply the number by 2. We print the result, which is now 2.460000038 with the desired precision.
Package library: math/big package if for arbitrary-precision arithmetic in Go.
Golang Rat.Float64 - 18 examples found. These are the top rated real world Golang examples of math/big.Rat.Float64 extracted from open source projects. You can rate examples to help us improve the quality of examples.