Brian Hoffman
Brian Hoffman

Reputation: 133

How to convert scientific notation string to a big.Int?

In golang I have a large number in a string like this: "4.49955000449955e+24".

How can I convert this to a big.Int?

Upvotes: 2

Views: 6629

Answers (1)

hobbs
hobbs

Reputation: 239980

use big.ParseFloat to get a big.Float and then the Int method to convert it to a big.Int:

flt, _, err := big.ParseFloat(input, 10, 0, big.ToNearestEven)
if err != nil {
    /* handle a parsing error here */
}
var i = new(big.Int)
i, acc := flt.Int(i)

see it on the Go Playground.

By adjusting the prec argument to ParseFloat you can control the precision of the intermediate float — it takes at least 72 bits of precision for your example input to come out exactly (to a value ending in ten zeroes) but the default if you pass 0 is 64 bits.

Upvotes: 8

Related Questions