英文:
Is there a safe way to cast float64 to int64 in Go?
问题
我知道Go语言提供了int()
或int64()
类型转换函数。在将float64
转换为int64
时,是否有一种安全的方式(带截断),考虑到最大可表示的64位浮点数math.MaxFloat64
比math.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.MaxInt64
和math.MinInt64
的最接近的双精度整数值进行比较。这些数字无法精确地存储在float64
值中,但它们将被存储为比这些数字稍大或稍小的下一个整数值:
float64(math.MaxInt64) // 9223372036854775808
float64(math.MinInt64) // -9223372036854775808
因此,只要你的float64
值介于这两个值之间,你就知道它可以在不溢出的情况下转换为int64
。
但请注意,如果你要进行相反的转换,不能保证float64
能够准确表示所有小于等于MaxInt64
的int64
值,因为双精度浮点值只能保留52位精度。在这种情况下,你必须检查int64
值是否介于-1<<53
和1<<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<<53
and 1<<53
.
In either case you can handle larger values with the math/big
package.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论