Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected Floating Point Precision Issue When Multiplying by 100 #222

Open
jigexiansen opened this issue Aug 9, 2024 · 1 comment
Open

Comments

@jigexiansen
Copy link

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:

  1. 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
    }
  2. 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!

@Baxromumarov
Copy link

Baxromumarov commented Aug 12, 2024

This issue is not related to this cast package. It is golang float64 case. You can try it
`
package main

import (
"fmt"
)

func main() {
var floatValue float32 = 19.9
fmt.Println(floatValue * 100) // 1989.9999999999998
}
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants