Home >Backend Development >Golang >Why Does Converting float64 to int in Go Produce Unexpected Results?
Converting floating-point numbers (float64) to integers (int) in Go can lead to unexpected results due to the limitations of floating-point representation.
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.
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.
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!