How to avoid precision loss in Golang
In Golang, due to the characteristics of floating point calculations, precision loss sometimes occurs. This article will share some methods to avoid precision loss in Golang and provide specific code examples.
Golang’s float64 type may lose precision when dealing with decimals. To avoid this situation, we can use the Decimal type in the third-party library github.com/shopspring/decimal
instead of float64.
package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { num1 := decimal.NewFromFloat(0.1) num2 := decimal.NewFromFloat(0.2) sum := num1.Add(num2) fmt.Println(sum) }
Another way to avoid loss of precision is to convert decimals to integers for calculations, and then convert the results back to decimals.
package main import "fmt" func main() { num1 := 1.23 num2 := 4.56 precision := 1000000 // 精度为小数点后六位 intNum1 := int(num1 * float64(precision)) intNum2 := int(num2 * float64(precision)) sum := intNum1 + intNum2 result := float64(sum) / float64(precision) fmt.Println(result) }
If you need to process very large integers, you can use Golang’s built-in math/big
package for calculations. Avoid the problem of loss of accuracy.
package main import ( "fmt" "math/big" ) func main() { num1 := new(big.Int) num1.SetString("12345678901234567890", 10) num2 := new(big.Int) num2.SetString("98765432109876543210", 10) sum := new(big.Int) sum.Add(num1, num2) fmt.Println(sum) }
Through the above method, we can avoid the problem of precision loss in Golang and ensure that our calculation results are accurate. This article may help you.
The above is the detailed content of Ways to avoid precision loss in Golang. For more information, please follow other related articles on the PHP Chinese website!