Home >Backend Development >Golang >How to Safely Convert float64 to uint64 in Go?
When attempting to convert a float64 number to a uint64 in Go, precision issues can arise. This often results in unexpected behavior, as the fractional component of the float64 is discarded during the conversion.
To illustrate the issue:
package main import "fmt" func main() { var n float64 = 6161047830682206209 fmt.Println(uint64(n)) }
This code will print the following incorrect value:
6161047830682206208
The Problem
The root of the problem lies in the differences between how constants and floating-point numbers are represented in Go. Constants are represented with arbitrary precision, while floating-point numbers follow the IEEE 754 standard. This means that while constants can represent values without precision loss, floating-point numbers have a limited number of bits (53 for float64) available for storing digits.
The Solution
To correctly convert a float64 to a uint64, you must ensure that the float64 number can be precisely represented within the 52 bits available. Otherwise, precision will be lost. You can do this by verifying that the float64 value is within the representable range of uint64.
Below is an example of a function that checks the representability before casting:
func Float64ToUint64(n float64) (uint64, error) { if (n < 0) || (n > math.MaxUint64) { return 0, errors.New("value out of range") } return uint64(n), nil }
The above is the detailed content of How to Safely Convert float64 to uint64 in Go?. For more information, please follow other related articles on the PHP Chinese website!