简体   繁体   中英

big.Float GetString without rounding

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM