Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert golang math/big int to float?

Tags:

go

I'm using Go's big.Int as counters in a long running service where the statistics counters might overflow a regular uint64 over a long run. Occasionally I need to calculate something like, "what's the average rate since program beginning?", needing a division like float64(big.Int) / time.Since(beginning).Seconds(); the precision loss of conversion is acceptable in the rate calculation.

But this kind of float64(big.Int) conversion doesn't work. I see the package has a big.Int.Uint64 conversion method but it's undefined if the value overflows a regular uint64. I wonder why the standard library doesn't provide a to Float64() method and is there any workaround how to get a floating point value?

like image 879
user5672998 Avatar asked Feb 27 '17 20:02

user5672998


1 Answers

You can convert a big.Int to a big.Float using the Float.SetInt method.

i := big.NewInt(12345)
f := new(big.Float).SetInt(i)

Then you can either convert f as a float64 with the accepted accuracy, or use the big.Float methods to calculate the output with greater accuracy.

like image 106
JimB Avatar answered Nov 15 '22 05:11

JimB