Home > Backend Development > Golang > How to Accurately Convert a float64 to a uint64 in Go?

How to Accurately Convert a float64 to a uint64 in Go?

DDD
Release: 2024-12-20 00:12:27
Original
127 people have browsed it

How to Accurately Convert a float64 to a uint64 in Go?

How to Convert a Float64 Number to UInt64 Properly

Consider the following Go code:

package main

func main() {
    var n float64 = 6161047830682206209
    println(uint64(n))
}
Copy after login

The expected output is to convert the float64 number to a uint64, preserving the value. However, the actual output is 6161047830682206208, indicating that the fractional part is discarded.

Understanding the Issue

The discrepancy arises due to the precision limitations of floating-point numbers represented using the IEEE 754 standard. In IEEE 754, 53 bits are allocated for storing the digits in a 64-bit floating-point number (float64 in Go). For the given constant, the number of digits that can be represented is less than the number of digits in the constant itself.

Therefore, the constant cannot be stored precisely in a float64 variable, and some digits are rounded and lost. This can be confirmed by printing the original n float64 number:

fmt.Printf("%f\n", n)
fmt.Printf("%d\n", uint64(n))
Copy after login

Correct Conversion

To convert a float64 number to a uint64 properly, it is recommended to use the Trunc function, which truncates the fractional part of a float64 number and returns the integer part:

package main

import "math"

func main() {
    var n float64 = 6161047830682206209
    println(uint64(math.Trunc(n)))
}
Copy after login

This approach ensures that the integer value is converted without any loss of precision.

The above is the detailed content of How to Accurately Convert a float64 to a uint64 in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template