Skip to content

Commit

Permalink
feat: add precUint (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
quagmt authored Oct 17, 2024
1 parent 603c3aa commit 5d3d0ff
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
13 changes: 13 additions & 0 deletions decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,19 @@ func (d Decimal) Prec() int {
return int(d.prec)
}

// PrecUint returns decimal precision as uint8
// Useful when you want to use the precision
// in other functions like Round or Trunc because they accept uint8
//
// Example:
//
// u := MustParse("0.000001")
// d := MustParse("123.4567891") // 123.456, prec = 3
// d = d.Trunc(u.PrecUint()) // 123.456789
func (d Decimal) PrecUint() uint8 {
return d.prec
}

// Cmp compares two decimals d,e and returns:
//
// -1 if d < e
Expand Down
31 changes: 31 additions & 0 deletions decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2290,3 +2290,34 @@ func TestCmpWithDiffPrec(t *testing.T) {
})
}
}

func TestPrecUint(t *testing.T) {
testcases := []struct {
a string
want uint8
}{
{"0", 0},
{"0.123456789", 9},
{"-0.123456789", 9},
{"-123456789.123456789", 9},
{"1234567890123456789.1234567890123456789", 19},
{"-1234567890123456789.1234567890123456789", 19},
{"123456789123456789123456789.1234567890123456789", 19},
{"-123456789123456789123456789.1234567890123456789", 19},
}

oneUnit := MustParse("0.0001")

for _, tc := range testcases {
t.Run(fmt.Sprintf("precUint(%s)", tc.a), func(t *testing.T) {
a := MustParse(tc.a)
require.Equal(t, tc.want, a.PrecUint())

b := a.Trunc(oneUnit.PrecUint())
if a.prec > oneUnit.prec {
require.Equal(t, oneUnit.prec, b.PrecUint())
}
})

}
}
6 changes: 6 additions & 0 deletions doc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,12 @@ func ExampleDecimal_Prec() {
// 2
}

func ExampleDecimal_PrecUint() {
fmt.Println(MustParse("1.23456").PrecUint())
// Output:
// 5
}

func ExampleDecimal_RoundBank() {
fmt.Println(MustParse("1.12345").RoundBank(4))
fmt.Println(MustParse("1.12335").RoundBank(4))
Expand Down

0 comments on commit 5d3d0ff

Please sign in to comment.