spf13 / spf13/cast

Unexpected Floating Point Precision Issue When Multiplying by 100

Open
#222 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Go
Stars
4k
Forks
337
Avg merge
15m
Merged PRs (30d)
1

Description

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!

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the Go reproduction in the issue and inspecting the behavior of cast.ToFloat64 with the supplied string. No repository file or test is named; completion would require determining whether the reported result is within the library's scope and documenting a concrete, accepted outcome.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
tooling
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
15/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.