Skip to content

proposal: math/big: Comparison to arbitrary number of decimal points #71288

@chaslain

Description

@chaslain

Proposal Details

When representing arbitrary precision to compare two decimal money values, I have come to realize that sometimes the following code:

fmt.Println(float1.String() + " " + float2.String())
fmt.Println(float1.Cmp(float2))

Can have the output

804.26 804.26
-1

I would classify this as an unexpected result.
[For context, float1 is the sum of big floats parsed from strings, each string is formatted matching the regex "\d+.\d\d"]
At some point, during adding, the internal mantissas does not match, triggering comparison to view the values as not equal.

In this specific case, this code gets around the problem:

float1.SetString(float1.String())
float2.SetString(float2.String())
float1.Cmp(float2)

I propose an arbitrary precision comparison similar to the PHP arbitrary precision library, which allows comparison down to a specific number of digits.
I realize that base 10 are a human concept and not a machine one, and likely string manipulation will be required to compare the values.

Proposal:

// CmpArbitrary Compares to a specific digit in base 10. If places is negative, digits to the left of the decimal are truncated. If places is positive, all 
// digits to the right of the decimal except to that place are truncated.
// if places is 0, the floats are compared as integers.
func (x* big.Float) CmpArbitrary(y *big.Float, z *big.Float, places int) int {
// some implementation
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeLibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolProposal

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions