Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

big.Float GetString without rounding

Tags:

go

I want to see the result: "3891113451447590234" without "3891113451447590400"

bigI,_ := big.NewInt(0).SetString("3891113451447590234", 10)
bigF := big.NewFloat(0).SetInt(bigI)
fmt.Println(bigF)
fmt.Println(bigF.String())
fmt.Println(bigF.SetMode(big.AwayFromZero).Text('f', 8))
fmt.Println(bigF.SetMode(big.AwayFromZero).Text('g', 20))

3.8911134514475904e+18
3.891113451e+18
3891113451447590400.00000000
3891113451447590400
like image 989
TomX01 Avatar asked Mar 14 '26 16:03

TomX01


1 Answers

The big.NewFloat function sets the default precision to 53.

NewFloat allocates and returns a new Float set to x, with precision 53 and rounding mode ToNearestEven. NewFloat panics with ErrNaN if x is a NaN.

If you want to set values with higher precision, you can set the precision directly, or you can start with precision 0 using a zero value of big.Float which determines the required precision when the value is first set.

f1, _, _ := new(big.Float).SetPrec(128).SetMode(big.ToNearestEven).Parse("3891113451447590234", 10)
// equivalent to
// big.ParseFloat("3891113451447590234", 10, 128, big.ToZero)
fmt.Println(f1)
// 3.891113451447590234e+18

i, _ = new(big.Int).SetString("3891113451447590234", 10)
f2 = new(big.Float).SetInt(i)
fmt.Println(f2)
// 3.891113451447590234e+18
like image 77
JimB Avatar answered Mar 17 '26 10:03

JimB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!