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
Release: 2024-12-14 22:11:12
Original
750 people have browsed it

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)))
}
Copy after login

Running this code will print:

0.5499999999999972
Copy after login

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)
}
Copy after login

This code prints:

0.55
Copy after login

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)
Copy after login

This code prints:

100.55 $
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template