fix formatString

This commit is contained in:
c9s 2022-02-25 18:25:44 +08:00
parent 99b025dd5c
commit 9c45e6693f
3 changed files with 17 additions and 13 deletions

View File

@ -111,8 +111,8 @@ func (v Value) FormatPercentage(prec int) string {
if v == 0 { if v == 0 {
return "0" return "0"
} }
result := strconv.FormatFloat(float64(v)/DefaultPow*100., 'f', prec+1, 64) result := strconv.FormatFloat(float64(v)/DefaultPow*100., 'f', prec, 64)
return result[:len(result)-1] + "%" return result + "%"
} }
func (v Value) SignedPercentage() string { func (v Value) SignedPercentage() string {

View File

@ -273,7 +273,11 @@ func (dn Value) FormatString(prec int) string {
return sign + digits[:dec] + "." + digits[dec:min(dec+prec, nd)] + strings.Repeat("0", max(0, min(dec+prec, nd)-dec-prec)) return sign + digits[:dec] + "." + digits[dec:min(dec+prec, nd)] + strings.Repeat("0", max(0, min(dec+prec, nd)-dec-prec))
} else if 0 < dn.exp && dn.exp <= digitsMax { } else if 0 < dn.exp && dn.exp <= digitsMax {
// decimal to the right // decimal to the right
return sign + digits + strings.Repeat("0", e) + "." + strings.Repeat("0", prec) if prec > 0 {
return sign + digits + strings.Repeat("0", e) + "." + strings.Repeat("0", prec)
} else {
return sign + digits + strings.Repeat("0", e)
}
} else { } else {
// scientific notation // scientific notation
after := "" after := ""

View File

@ -74,28 +74,28 @@ func TestNew(t *testing.T) {
func TestFormatString(t *testing.T) { func TestFormatString(t *testing.T) {
testCases := []struct { testCases := []struct {
value Value value Value
prec int prec int
out string out string
}{ }{
{ {
value: NewFromFloat(0.001), value: NewFromFloat(0.001),
prec: 8, prec: 8,
out: "0.00100000", out: "0.00100000",
}, },
{ {
value: NewFromFloat(0.123456789), value: NewFromFloat(0.123456789),
prec: 4, prec: 4,
out: "0.1234", out: "0.1234",
}, },
{ {
value: NewFromFloat(0.123456789), value: NewFromFloat(0.123456789),
prec: 5, prec: 5,
out: "0.12345", out: "0.12345",
}, },
{ {
value: NewFromFloat(20.0), value: NewFromFloat(20.0),
prec: 0, prec: 0,
out: "20", out: "20",
}, },
} }
for _, testCase := range testCases { for _, testCase := range testCases {