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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With