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 {
return "0"
}
result := strconv.FormatFloat(float64(v)/DefaultPow*100., 'f', prec+1, 64)
return result[:len(result)-1] + "%"
result := strconv.FormatFloat(float64(v)/DefaultPow*100., 'f', prec, 64)
return result + "%"
}
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))
} else if 0 < dn.exp && dn.exp <= digitsMax {
// 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 {
// scientific notation
after := ""

View File

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