Home >Backend Development >Golang >Why Does Converting float64 to int in Go Produce Unexpected Results?

Why Does Converting float64 to int in Go Produce Unexpected Results?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-14 22:11:12747browse

Why Does Converting float64 to int in Go Produce Unexpected Results?

Error Converting float64 to int in Go

Introduction

Converting floating-point numbers (float64) to integers (int) in Go can lead to unexpected results due to the limitations of floating-point representation.

Understanding the Problem

Decimal numbers like 100.55 cannot be precisely represented using a finite number of bits in binary, the internal representation used by computers. Float64 values in Go conform to the IEEE-754 standard, which uses 53 bits for the fractional part. This means that 100.55 is approximated to the nearest representable binary number, leading to slight discrepancies.

Example

Consider the following code:

package main

import "fmt"

func main() {
    x := 100.55
    fmt.Println(x - float64(int(x)))
}

Running this code will print:

0.5499999999999972

instead of the expected 0.55.

Solution

String Formatters (fmt.Printf)

One way to handle this discrepancy is to round the floating-point number to the desired precision before printing.

package main

import "fmt"

func main() {
    x := 100.55
    fmt.Printf("%.2f\n", x)
}

This code prints:

0.55

Non-Floating-Point Representation

Another approach is to avoid using floating-point numbers altogether. For example, to represent dollar amounts, you could use cents as integers and scale by 100 when displaying.

cents := 10055
fmt.Printf("%d.%d $\n", cents/100, cents%100)

This code prints:

100.55 $

The above is the detailed content of Why Does Converting float64 to int in Go Produce Unexpected Results?. 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