简体   繁体   中英

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

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?

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.

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