fix: fixedpoint percentage bound check

This commit is contained in:
zenix 2022-06-13 11:05:55 +09:00
parent 77e8af2ae6
commit a65374d686
2 changed files with 12 additions and 3 deletions

View File

@ -350,14 +350,14 @@ func (dn Value) Percentage() string {
nd := len(digits)
e := int(dn.exp) - nd + 2
if -maxLeadingZeros <= dn.exp && dn.exp <= 0 {
if -maxLeadingZeros <= dn.exp && dn.exp <= -2 {
// decimal to the left
return sign + "0." + strings.Repeat("0", -e-nd) + digits + "%"
} else if -nd < e && e <= -1 {
// decimal within
dec := nd + e
return sign + digits[:dec] + "." + digits[dec:]
} else if 0 < dn.exp && dn.exp <= digitsMax {
return sign + digits[:dec] + "." + digits[dec:] + "%"
} else if -2 < dn.exp && dn.exp <= digitsMax {
// decimal to the right
return sign + digits + strings.Repeat("0", e) + "%"
} else {

View File

@ -69,6 +69,15 @@ func TestNew(t *testing.T) {
assert.Equal(t, "0.0010", f.FormatString(4))
assert.Equal(t, "0.1%", f.Percentage())
assert.Equal(t, "0.10%", f.FormatPercentage(2))
f = NewFromFloat(0.1)
assert.Equal(t, "10%", f.Percentage())
assert.Equal(t, "10%", f.FormatPercentage(0))
f = NewFromFloat(0.01)
assert.Equal(t, "1%", f.Percentage())
assert.Equal(t, "1%", f.FormatPercentage(0))
f = NewFromFloat(0.111)
assert.Equal(t, "11.1%", f.Percentage())
assert.Equal(t, "11.1%", f.FormatPercentage(1))
}
func TestFormatString(t *testing.T) {