cast
cast copied to clipboard
Unexpected Floating Point Precision Issue When Multiplying by 100
I encountered an unexpected behavior when converting a string to a float64
and then performing a multiplication operation. The result seems to have a precision issue.
Steps to Reproduce:
-
Use the following code snippet:
package main import ( "fmt" "github.com/spf13/cast" ) func main() { strValue := "19.9" floatValue := cast.ToFloat64(strValue) // 19.9 fmt.Println(floatValue) // 19.9 fmt.Println(floatValue * 100) // 1989.9999999999998 }
-
Run the code.
Expected Behavior:
The output should be:
19.9
1990
Actual Behavior:
The output is:
19.9
1989.9999999999998
Additional Context:
- Go version:
go1.22.5
- Operating System:
Darwin 23.5.0 arm64
-
github.com/spf13/cast
version:v1.7.0
It seems like there is a floating point precision issue when multiplying the float64
value by 100. Is this the expected behavior due to the nature of floating point arithmetic in Go, or is there a way to handle this more accurately?
Thank you for your assistance!