在Go语言中,将float64转换为int64有一种安全的方法吗?

huangapple go评论111阅读模式
英文:

Is there a safe way to cast float64 to int64 in Go?

问题

我知道Go语言提供了int()int64()类型转换函数。在将float64转换为int64时,是否有一种安全的方式(带截断),考虑到最大可表示的64位浮点数math.MaxFloat64math.MaxInt64要大得多?有一种方式可以触发溢出错误吗?

英文:

I am aware of the int() or int64() typecast functions, the Go provides.
Is there a safe way to cast float64 to int64 (with truncation,) given the largest representable 64-bit floating point number math.MaxFloat64 is much larger than math.MaxInt64? A way, that triggers an overflow error?

答案1

得分: 2

如果你要从float64转换为int64(而不是强制转换或类型转换),那么你可以将浮点值与math.MaxInt64math.MinInt64的最接近的双精度整数值进行比较。这些数字无法精确地存储在float64值中,但它们将被存储为比这些数字稍大或稍小的下一个整数值:

float64(math.MaxInt64) // 9223372036854775808
float64(math.MinInt64) // -9223372036854775808

因此,只要你的float64值介于这两个值之间,你就知道它可以在不溢出的情况下转换为int64

但请注意,如果你要进行相反的转换,不能保证float64能够准确表示所有小于等于MaxInt64int64值,因为双精度浮点值只能保留52位精度。在这种情况下,你必须检查int64值是否介于-1<<531<<53之间。

无论哪种情况,你都可以使用math/big包处理更大的值。

英文:

If you are converting (not casting or typecasting) from a float64 to an int64, then you can compare the float value to the closest double precision integer values of math.MaxInt64 and math.MinInt64. These numbers cannot be exactly stored in a float64 value, however they will be stored as the next integer value above or below those:

float64(math.MaxInt64) // 9223372036854775808
float64(math.MinInt64) // -9223372036854775808

So as long as your float64 value is between these two values, you know it can be converted to an int64 without overflow.

Note however that if you are converting in the other direction, you cannot guarantee that a float64 can accurately represent all int64 values up to MaxInt64, since a double precision float point value only holds 52 bits of precision. In that case you must check that the int64 value is between -1&lt;&lt;53 and 1&lt;&lt;53.

In either case you can handle larger values with the math/big package.

huangapple
  • 本文由 发表于 2023年1月28日 21:18:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75267933.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定