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

How to Safely Convert float64 to uint64 in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 02:44:10212browse

How to Safely Convert float64 to uint64 in Go?

Correctly Converting float64 to uint64

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!

Statement:
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