Compare commits

...

3 commits

Author SHA1 Message Date
Jim McDonald
7541e49cff
Merge c31da0254a into d00399e161 2024-02-19 21:37:10 -07:00
Dovydas
d00399e161
Add NewFromBigRat constructor (#288) 2024-02-19 23:13:43 +01:00
Jim McDonald
c31da0254a
Add Format() 2022-04-11 17:45:30 +01:00
2 changed files with 174 additions and 42 deletions

View file

@ -124,6 +124,26 @@ func NewFromBigInt(value *big.Int, exp int32) Decimal {
} }
} }
// NewFromBigRat returns a new Decimal from a big.Rat. The numerator and
// denominator are divided and rounded to the given precision.
//
// Example:
//
// d1 := NewFromBigRat(big.NewRat(0, 1), 0) // output: "0"
// d2 := NewFromBigRat(big.NewRat(4, 5), 1) // output: "0.8"
// d3 := NewFromBigRat(big.NewRat(1000, 3), 3) // output: "333.333"
// d4 := NewFromBigRat(big.NewRat(2, 7), 4) // output: "0.2857"
//
func NewFromBigRat(value *big.Rat, precision int32) Decimal {
return Decimal{
value: new(big.Int).Set(value.Num()),
exp: 0,
}.DivRound(Decimal{
value: new(big.Int).Set(value.Denom()),
exp: 0,
}, precision)
}
// NewFromString returns a new Decimal from a string representation. // NewFromString returns a new Decimal from a string representation.
// Trailing zeroes are not trimmed. // Trailing zeroes are not trimmed.
// //
@ -1145,6 +1165,73 @@ func (d Decimal) String() string {
return d.string(true) return d.string(true)
} }
// Format formats a decimal.
// thousandsSeparator can be empty, in which case the integer value will be displayed without separation.
// if decimalSeparator is empty and the value is a decimal this will panic.
func (d Decimal) Format(thousandsSeparator string, decimalSeparator string, trimTrailingZeros bool) string {
if d.exp >= 0 {
d = d.rescale(0)
}
abs := new(big.Int).Abs(d.value)
str := abs.String()
var intPart, fractionalPart string
// NOTE(vadim): this cast to int will cause bugs if d.exp == INT_MIN
// and you are on a 32-bit machine. Won't fix this super-edge case.
dExpInt := int(d.exp)
if len(str) > -dExpInt {
intPart = str[:len(str)+dExpInt]
fractionalPart = str[len(str)+dExpInt:]
} else {
intPart = "0"
num0s := -dExpInt - len(str)
fractionalPart = strings.Repeat("0", num0s) + str
}
if thousandsSeparator != "" {
parts := 1 + (len(intPart)-1)/3
if parts > 1 {
intParts := make([]string, 1+(len(intPart)-1)/3)
offset := len(intPart) - (len(intParts)-1)*3
for i := 0; i < len(intParts); i++ {
if i == 0 {
intParts[i] = intPart[0:offset]
} else {
intParts[i] = intPart[(i-1)*3+offset : i*3+offset]
}
}
intPart = strings.Join(intParts, thousandsSeparator)
}
}
if trimTrailingZeros {
i := len(fractionalPart) - 1
for ; i >= 0; i-- {
if fractionalPart[i] != '0' {
break
}
}
fractionalPart = fractionalPart[:i+1]
}
if fractionalPart != "" && decimalSeparator == "" {
panic("no decimal separator for non-integer")
}
number := intPart
if len(fractionalPart) > 0 {
number += decimalSeparator + fractionalPart
}
if d.value.Sign() < 0 {
return "-" + number
}
return number
}
// StringFixed returns a rounded fixed-point string with places digits after // StringFixed returns a rounded fixed-point string with places digits after
// the decimal point. // the decimal point.
// //
@ -1575,48 +1662,7 @@ func (d Decimal) StringScaled(exp int32) string {
} }
func (d Decimal) string(trimTrailingZeros bool) string { func (d Decimal) string(trimTrailingZeros bool) string {
if d.exp >= 0 { return d.Format("", ".", trimTrailingZeros)
return d.rescale(0).value.String()
}
abs := new(big.Int).Abs(d.value)
str := abs.String()
var intPart, fractionalPart string
// NOTE(vadim): this cast to int will cause bugs if d.exp == INT_MIN
// and you are on a 32-bit machine. Won't fix this super-edge case.
dExpInt := int(d.exp)
if len(str) > -dExpInt {
intPart = str[:len(str)+dExpInt]
fractionalPart = str[len(str)+dExpInt:]
} else {
intPart = "0"
num0s := -dExpInt - len(str)
fractionalPart = strings.Repeat("0", num0s) + str
}
if trimTrailingZeros {
i := len(fractionalPart) - 1
for ; i >= 0; i-- {
if fractionalPart[i] != '0' {
break
}
}
fractionalPart = fractionalPart[:i+1]
}
number := intPart
if len(fractionalPart) > 0 {
number += "." + fractionalPart
}
if d.value.Sign() < 0 {
return "-" + number
}
return number
} }
func (d *Decimal) ensureInitialized() { func (d *Decimal) ensureInitialized() {

View file

@ -556,6 +556,51 @@ func TestNewFromBigIntWithExponent(t *testing.T) {
} }
} }
func TestNewFromBigRat(t *testing.T) {
mustParseRat := func(val string) *big.Rat {
num, _ := new(big.Rat).SetString(val)
return num
}
type Inp struct {
val *big.Rat
prec int32
}
tests := map[Inp]string{
Inp{big.NewRat(0, 1), 16}: "0",
Inp{big.NewRat(4, 5), 16}: "0.8",
Inp{big.NewRat(10, 2), 16}: "5",
Inp{big.NewRat(1023427554493, 43432632), 16}: "23563.5628642767953828", // rounded
Inp{big.NewRat(1, 434324545566634), 16}: "0.0000000000000023",
Inp{big.NewRat(1, 3), 16}: "0.3333333333333333",
Inp{big.NewRat(2, 3), 2}: "0.67", // rounded
Inp{big.NewRat(2, 3), 16}: "0.6666666666666667", // rounded
Inp{big.NewRat(10000, 3), 16}: "3333.3333333333333333",
Inp{mustParseRat("30702832066636633479"), 16}: "30702832066636633479",
Inp{mustParseRat("487028320159896636679.1827512895753"), 16}: "487028320159896636679.1827512895753",
Inp{mustParseRat("127028320612589896636633479.173582751289575278357832"), -2}: "127028320612589896636633500", // rounded
Inp{mustParseRat("127028320612589896636633479.173582751289575278357832"), 16}: "127028320612589896636633479.1735827512895753", // rounded
Inp{mustParseRat("127028320612589896636633479.173582751289575278357832"), 32}: "127028320612589896636633479.173582751289575278357832",
}
// add negatives
for p, s := range tests {
if p.val.Cmp(new(big.Rat)) > 0 {
tests[Inp{p.val.Neg(p.val), p.prec}] = "-" + s
}
}
for input, s := range tests {
d := NewFromBigRat(input.val, input.prec)
if d.String() != s {
t.Errorf("expected %s, got %s (%s, %d)",
s, d.String(),
d.value.String(), d.exp)
}
}
}
func TestCopy(t *testing.T) { func TestCopy(t *testing.T) {
origin := New(1, 0) origin := New(1, 0)
cpy := origin.Copy() cpy := origin.Copy()
@ -1468,6 +1513,47 @@ func TestDecimal_RoundDownAndStringFixed(t *testing.T) {
} }
} }
func TestDecimal_Format(t *testing.T) {
type testData struct {
input string
thousandsSeparator string
decimalSeparator string
trimTrailingZeros bool
expected string
}
tests := []testData{
{"0", ",", ".", false, "0"},
{"0", ",", ".", true, "0"},
{"999", ",", ".", true, "999"},
{"1000", ",", ".", true, "1,000"},
{"123", ",", ".", true, "123"},
{"1234", ",", ".", true, "1,234"},
{"12345.67", "", ".", true, "12345.67"},
{"12345.00", ",", ".", true, "12,345"},
{"12345.00", ",", ".", false, "12,345.00"},
{"123456.00", ",", ".", false, "123,456.00"},
{"1234567.00", ",", ".", false, "1,234,567.00"},
{"1234567.00", ".", ",", false, "1.234.567,00"},
{"1234567.00", "_", ".", true, "1_234_567"},
{"-12.00", "_", ".", true, "-12"},
{"-123.00", "_", ".", true, "-123"},
{"-1234.00", "_", ".", true, "-1_234"},
}
for _, test := range tests {
d, err := NewFromString(test.input)
if err != nil {
panic(err)
}
got := d.Format(test.thousandsSeparator, test.decimalSeparator, test.trimTrailingZeros)
if got != test.expected {
t.Errorf("Format %s got %s, expected %s",
d, got, test.expected)
}
}
}
func TestDecimal_BankRoundAndStringFixed(t *testing.T) { func TestDecimal_BankRoundAndStringFixed(t *testing.T) {
type testData struct { type testData struct {
input string input string