Skip to content

Commit

Permalink
Fix precision bug on formatted numbers.
Browse files Browse the repository at this point in the history
  • Loading branch information
marcopaganini committed Nov 17, 2024
1 parent 3c7b38f commit 3be8819
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
9 changes: 5 additions & 4 deletions decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ func commafWithDigits(v *decimal.Big, decimals int) string {

comma := []byte{','}

parts := strings.Split(fmt.Sprintf("%f", v), ".")
f := fmt.Sprintf("%%.%df", decimals)
parts := strings.Split(fmt.Sprintf(f, v), ".")

pos := 0
if len(parts[0])%3 != 0 {
Expand Down Expand Up @@ -95,8 +96,8 @@ func formatNumber(ctx decimal.Context, n *decimal.Big, base, decimals int) strin
}

// clean = double as ascii, without non-significant decimal zeroes.
fm := fmt.Sprintf("%%.%df", decimals)
clean := stripTrailingDigits(fmt.Sprintf(fm, n), decimals)
f := fmt.Sprintf("%%.%df", decimals)
clean := stripTrailingDigits(fmt.Sprintf(f, n), decimals)

var (
n64 uint64
Expand Down Expand Up @@ -132,7 +133,7 @@ func formatNumber(ctx decimal.Context, n *decimal.Big, base, decimals int) strin
case base == 16:
buf.WriteString(fmt.Sprintf("0x%x%s", n64, suffix))
default:
h := commafWithDigits(n, decimals) // FIXME find out how to deal with precision properly.
h := commafWithDigits(n, decimals)
// Only print humanized format when it differs from original value.
if h != clean {
suffix = " (" + h + ")"
Expand Down
1 change: 1 addition & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ func TestFormatNumber(t *testing.T) {
{10, bigUint(1000000000000000), "1000000000000000 (1,000,000,000,000,000)"},
{10, bigFloat("10000.333333"), "10000.333333 (10,000.333333)"},
{10, bigFloat("-10000.333333"), "-10000.333333 (-10,000.333333)"},
{10, ctx.Quo(big(), bigUint(567), bigUint(999)), "0.567568"},
{10, ctx.Pow(big(), bigUint(2), bigUint(64)), "18446744073709551616 (18,446,744,073,709,551,616)"},
{10, ctx.Pow(big(), bigUint(2), bigUint(1234567890)), "Infinity"},
{10, ctx.Quo(big(), bigUint(0), bigUint(0)), "NaN"},
Expand Down

0 comments on commit 3be8819

Please # to comment.