From 3be8819561ad81a588021de08ec2764691625da1 Mon Sep 17 00:00:00 2001 From: Marco Paganini Date: Sun, 17 Nov 2024 12:00:15 -0800 Subject: [PATCH] Fix precision bug on formatted numbers. --- decimal.go | 9 +++++---- main_test.go | 1 + 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/decimal.go b/decimal.go index fcd63f1..c8e42f3 100644 --- a/decimal.go +++ b/decimal.go @@ -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 { @@ -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 @@ -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 + ")" diff --git a/main_test.go b/main_test.go index ab77f25..da79d81 100644 --- a/main_test.go +++ b/main_test.go @@ -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"},