From 88212e6cfca9907e06daaaab52a2b5e566ca0b91 Mon Sep 17 00:00:00 2001 From: Kieran Gorman Date: Fri, 6 Dec 2019 04:24:08 +0000 Subject: [PATCH] format: fix precision when exponent > 0 (#148) Previously we would take only precision without also considering the exponent, meaning you would have scenarios like 200 being formatted with `%.2f` as just `200` as `x.exp` would be 2, and `x.Precision()` would be 1. --- big.go | 2 +- big_test.go | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/big.go b/big.go index 42c1299..d5908e7 100644 --- a/big.go +++ b/big.go @@ -629,7 +629,7 @@ func (x *Big) Format(s fmt.State, c rune) { } else { // %f's precision means "number of digits after the radix" if x.exp > 0 { - f.prec += x.Precision() + f.prec += (x.exp + x.Precision()) } else { if adj := x.exp + x.Precision(); adj > -f.prec { f.prec += adj diff --git a/big_test.go b/big_test.go index 8198e94..d6ba592 100644 --- a/big_test.go +++ b/big_test.go @@ -1,6 +1,7 @@ package decimal_test import ( + "fmt" "math" "math/big" "math/rand" @@ -268,3 +269,14 @@ got : %g } func isSpecial(f float64) bool { return math.IsInf(f, 0) || math.IsNaN(f) } + +func TestBig_Format(t *testing.T) { + x, _ := new(decimal.Big).SetString("200.0") + x.Reduce() + + y := fmt.Sprintf("%.2f", x) + + if y != "200.00" { + t.Fatalf("want 200.00 but had %s", y) + } +}