Add string method to numeric
This commit is contained in:
parent
2adb70fa01
commit
4c7c61e820
@ -92,6 +92,43 @@ func (n Numeric) Add(other Numeric) Numeric {
|
||||
panic("Cannot add with different exponents")
|
||||
}
|
||||
|
||||
func (n Numeric) String() string {
|
||||
if n.Int.Int64() == 0 {
|
||||
return "0"
|
||||
}
|
||||
|
||||
s := fmt.Sprintf("%d", n.Int)
|
||||
bytes := []byte(s)
|
||||
|
||||
exp := n.Exp
|
||||
for exp > 0 {
|
||||
bytes = append(bytes, byte('0'))
|
||||
exp--
|
||||
}
|
||||
|
||||
if exp == 0 {
|
||||
return string(bytes)
|
||||
}
|
||||
|
||||
length := int32(len(bytes))
|
||||
var bytesWithSeparator []byte
|
||||
|
||||
exp = -exp
|
||||
for length <= exp {
|
||||
bytes = append(bytes, byte('0'))
|
||||
length++
|
||||
}
|
||||
|
||||
split := length - exp
|
||||
bytesWithSeparator = append(bytesWithSeparator, bytes[:split]...)
|
||||
if split == 1 && n.Int.Int64() < 0 {
|
||||
bytesWithSeparator = append(bytesWithSeparator, byte('0'))
|
||||
}
|
||||
bytesWithSeparator = append(bytesWithSeparator, byte('.'))
|
||||
bytesWithSeparator = append(bytesWithSeparator, bytes[split:]...)
|
||||
return string(bytesWithSeparator)
|
||||
}
|
||||
|
||||
func (n Numeric) MarshalJSON() ([]byte, error) {
|
||||
if n.Int.Int64() == 0 {
|
||||
return []byte("0"), nil
|
||||
|
Loading…
x
Reference in New Issue
Block a user