Skip to content

Commit 88212e6

Browse files
Kieran Gormanericlagergren
authored andcommitted
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.
1 parent 98d6b4c commit 88212e6

2 files changed

Lines changed: 13 additions & 1 deletion

File tree

big.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -629,7 +629,7 @@ func (x *Big) Format(s fmt.State, c rune) {
629629
} else {
630630
// %f's precision means "number of digits after the radix"
631631
if x.exp > 0 {
632-
f.prec += x.Precision()
632+
f.prec += (x.exp + x.Precision())
633633
} else {
634634
if adj := x.exp + x.Precision(); adj > -f.prec {
635635
f.prec += adj

big_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package decimal_test
22

33
import (
4+
"fmt"
45
"math"
56
"math/big"
67
"math/rand"
@@ -268,3 +269,14 @@ got : %g
268269
}
269270

270271
func isSpecial(f float64) bool { return math.IsInf(f, 0) || math.IsNaN(f) }
272+
273+
func TestBig_Format(t *testing.T) {
274+
x, _ := new(decimal.Big).SetString("200.0")
275+
x.Reduce()
276+
277+
y := fmt.Sprintf("%.2f", x)
278+
279+
if y != "200.00" {
280+
t.Fatalf("want 200.00 but had %s", y)
281+
}
282+
}

0 commit comments

Comments
 (0)