FIX: fix format string float point issue

This commit is contained in:
chiahung 2023-03-10 15:27:50 +08:00
parent 78d65d74d2
commit 36f48bc604
3 changed files with 104 additions and 4 deletions

View File

@ -115,9 +115,50 @@ func (v Value) FormatString(prec int) string {
} else if v == NegInf { } else if v == NegInf {
return "-inf" return "-inf"
} }
pow := math.Pow10(prec)
return strconv.FormatFloat( u := int64(v)
math.Trunc(float64(v)/DefaultPow*pow)/pow, 'f', prec, 64)
// trunc precision
precDiff := DefaultPrecision - prec
if precDiff > 0 {
powDiff := int64(math.Pow10(precDiff))
u = int64(v) / powDiff * powDiff
}
// check sign
sign := Value(u).Sign()
basePow := int64(DefaultPow)
a := u / basePow
b := u % basePow
if a < 0 {
a = -a
}
if b < 0 {
b = -b
}
str := strconv.FormatInt(a, 10)
if prec > 0 {
bStr := fmt.Sprintf(".%08d", b)
if prec <= DefaultPrecision {
bStr = bStr[0 : prec+1]
} else {
for i := prec - DefaultPrecision; i > 0; i-- {
bStr += "0"
}
}
str += bStr
}
if sign < 0 {
str = "-" + str
}
return str
} }
func (v Value) Percentage() string { func (v Value) Percentage() string {

View File

@ -0,0 +1,59 @@
package fixedpoint
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_FormatString(t *testing.T) {
assert := assert.New(t)
t.Run("Value(57000000) with prec = 5, expected 0.57", func(t *testing.T) {
v := Value(57000000)
s := v.FormatString(5)
assert.Equal("0.57000", s)
})
t.Run("Value(57123456) with prec = 5, expected 0.57123", func(t *testing.T) {
v := Value(57123456)
s := v.FormatString(5)
assert.Equal("0.57123", s)
})
t.Run("Value(123456789) with prec = 9, expected 1.23456789", func(t *testing.T) {
v := Value(123456789)
s := v.FormatString(9)
assert.Equal("1.234567890", s)
})
t.Run("Value(102345678) with prec = 9, expected 1.02345678", func(t *testing.T) {
v := Value(102345678)
s := v.FormatString(9)
assert.Equal("1.023456780", s)
})
t.Run("Value(-57000000) with prec = 5, expected -0.57", func(t *testing.T) {
v := Value(-57000000)
s := v.FormatString(5)
assert.Equal("-0.57000", s)
})
t.Run("Value(-123456789) with prec = 9, expected 1.23456789", func(t *testing.T) {
v := Value(-123456789)
s := v.FormatString(9)
assert.Equal("-1.234567890", s)
})
t.Run("Value(1234567890) with prec = -1, expected 10", func(t *testing.T) {
v := Value(1234567890)
s := v.FormatString(-1)
assert.Equal("10", s)
})
t.Run("Value(-1234) with prec = 3, expected = 0.000", func(t *testing.T) {
v := Value(-1234)
s := v.FormatString(3)
assert.Equal("0.000", s)
})
}

View File

@ -113,7 +113,7 @@ func (m Market) FormatPrice(val fixedpoint.Value) string {
} }
func FormatPrice(price fixedpoint.Value, tickSize fixedpoint.Value) string { func FormatPrice(price fixedpoint.Value, tickSize fixedpoint.Value) string {
prec := int(math.Round(math.Abs(math.Log10(tickSize.Float64())))) prec := int(math.Round(math.Log10(tickSize.Float64()) * -1.0))
return price.FormatString(prec) return price.FormatString(prec)
} }