Merge pull request #712 from zenixls2/fix/fixedpoint_percentage

fix: fixedpoint percentage bound check
This commit is contained in:
Yo-An Lin 2022-06-13 10:15:46 +08:00 committed by GitHub
commit 8cf57cae29
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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) {