From 4c7c61e8200faad28bd7deb3664d92a893ed4146 Mon Sep 17 00:00:00 2001 From: Jan Bader Date: Wed, 23 Feb 2022 19:21:56 +0000 Subject: [PATCH] Add string method to numeric --- postgres/numeric.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/postgres/numeric.go b/postgres/numeric.go index f750a7b..cf8dea4 100644 --- a/postgres/numeric.go +++ b/postgres/numeric.go @@ -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