Skip to content

Commit

Permalink
format: fix precision when exponent > 0 (#148)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
kjgorman authored and ericlagergren committed Dec 6, 2019
1 parent 98d6b4c commit 88212e6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
2 changes: 1 addition & 1 deletion big.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions big_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package decimal_test

import (
"fmt"
"math"
"math/big"
"math/rand"
Expand Down Expand Up @@ -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)
}
}

0 comments on commit 88212e6

Please sign in to comment.