如何在字符串中存储一个大的float64而不会溢出? [英] How to store a big float64 in a string without overflow?

查看:94
本文介绍了如何在字符串中存储一个大的float64而不会溢出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

func main() {
        target := 20190201518310870.0
        fmt.Println(int64(target))
        z3 := big.NewInt(int64(target))
        fmt.Println(z3)
}

结果是20190201518310872

The result is 20190201518310872

我如何转换它而不产生溢出?

How do I convert it and not make overflow?

推荐答案

问题在于,即使您输入的target数字也不等于您为其分配的常数.

The problem is that even your input target number is not equal to the constant you assign to it.

float64类型使用双精度浮点格式(IEEE 754)来存储数字,该数字具有有限的位可使用(总共64位,但仅53位用于存储有效位数).这意味着它可以大致存储约16位数字,但是您输入的数字有17位,因此将四舍五入为最接近的可表示float64.

The float64 type uses the double-precision floating-point format (IEEE 754) to store the number, which has finite bits to utilize (64 bits in total, but only 53 bits are used to store the significand). This means it can roughly store ~16 digits, but your input number has 17, so it will be rounded to the nearest representable float64.

如果打印target,您将看到转移"到big.Int的确切号码:

If you print target, you will see the exact number that is "transfered" to big.Int:

target := 20190201518310870.0
fmt.Printf("%f\n", target)

输出(在游乐场上尝试):

20190201518310872.000000

请注意,如果输入常量适合" float64:

Note that it works if the input constant "fits" into float64:

target := 20190201518310.0
fmt.Printf("%f\n", target)
fmt.Println(int64(target))
z3 := big.NewInt(int64(target))
fmt.Println(z3)

输出(在游乐场上尝试):

20190201518310.000000
20190201518310
20190201518310

如果您需要使用完全相同的大数(例如20190201518310870.0),则必须使用另一种类型将其存储在第一位,例如stringbig.Intbig.Float,但不是float64.

If you need to work with big numbers exactly such as 20190201518310870.0, you have to use another type to store it in the first place, e.g. string, big.Int or big.Float, but not float64.

例如:

target := "20190201518310870"
fmt.Println(target)
z3, ok := big.NewInt(0).SetString(target, 10)
fmt.Println(z3, ok)

输出(在游乐场上尝试):

20190201518310870
20190201518310870 true

这篇关于如何在字符串中存储一个大的float64而不会溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆