Skip to content

Commit

Permalink
veqryn: add String() method to Decimal
Browse files Browse the repository at this point in the history
  • Loading branch information
veqryn committed Nov 8, 2024
1 parent c98e856 commit 8aac99e
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"encoding/binary"
"fmt"
"math/big"
"strings"

"github.com/mitchellh/mapstructure"
)
Expand Down Expand Up @@ -130,6 +131,36 @@ func (d *Decimal) Float64() float64 {
return f
}

func (d *Decimal) String() string {
// Get the sign, and return early if zero
if d.Value.Sign() == 0 {
return "0"
}

// Remove the sign from the string integer value
var signStr string
scaleless := d.Value.String()
if d.Value.Sign() < 0 {
signStr = "-"
scaleless = scaleless[1:]
}

// Remove all zeros from the right side
zeroTrimmed := strings.TrimRightFunc(scaleless, func(r rune) bool { return r == '0' })
scale := int(d.Scale) - (len(scaleless) - len(zeroTrimmed))

// If the string is still bigger than the scale factor, output it without a decimal point
if scale <= 0 {
return signStr + zeroTrimmed + strings.Repeat("0", -1*scale)
}

// Pad a number with 0.0's if needed
if len(zeroTrimmed) <= scale {
return fmt.Sprintf("%s0.%s%s", signStr, strings.Repeat("0", scale-len(zeroTrimmed)), zeroTrimmed)
}
return signStr + zeroTrimmed[:len(zeroTrimmed)-scale] + "." + zeroTrimmed[len(zeroTrimmed)-scale:]
}

func (d *Decimal) toString() string {
return fmt.Sprintf("DECIMAL(%d,%d)", d.Width, d.Scale)
}

0 comments on commit 8aac99e

Please sign in to comment.