Add NewFromInt and NewFromInt32 (#72)

Add NewFromInt and NewFromInt32
This commit is contained in:
Mathieu Post 2019-11-29 06:17:06 +01:00 committed by Jason Biegel
parent ff9ed33395
commit bc70c3beb9
3 changed files with 77 additions and 1 deletions

View file

@ -34,7 +34,7 @@ func main() {
panic(err) panic(err)
} }
quantity := decimal.NewFromFloat(3) quantity := decimal.NewFromInt(3)
fee, _ := decimal.NewFromString(".035") fee, _ := decimal.NewFromString(".035")
taxRate, _ := decimal.NewFromString(".08875") taxRate, _ := decimal.NewFromString(".08875")

View file

@ -87,6 +87,32 @@ func New(value int64, exp int32) Decimal {
} }
} }
// NewFromInt converts a int64 to Decimal.
//
// Example:
//
// NewFromInt(123).String() // output: "123"
// NewFromInt(-10).String() // output: "-10"
func NewFromInt(value int64) Decimal {
return Decimal{
value: big.NewInt(value),
exp: 0,
}
}
// NewFromInt32 converts a int32 to Decimal.
//
// Example:
//
// NewFromInt(123).String() // output: "123"
// NewFromInt(-10).String() // output: "-10"
func NewFromInt32(value int32) Decimal {
return Decimal{
value: big.NewInt(int64(value)),
exp: 0,
}
}
// NewFromBigInt returns a new Decimal from a big.Int, value * 10 ^ exp // NewFromBigInt returns a new Decimal from a big.Int, value * 10 ^ exp
func NewFromBigInt(value *big.Int, exp int32) Decimal { func NewFromBigInt(value *big.Int, exp int32) Decimal {
return Decimal{ return Decimal{

View file

@ -477,6 +477,56 @@ func TestNewFromFloatWithExponent(t *testing.T) {
} }
} }
func TestNewFromInt(t *testing.T) {
tests := map[int64]string{
0: "0",
1: "1",
323412345: "323412345",
9223372036854775807: "9223372036854775807",
}
// add negatives
for p, s := range tests {
if p > 0 {
tests[-p] = "-" + s
}
}
for input, s := range tests {
d := NewFromInt(input)
if d.String() != s {
t.Errorf("expected %s, got %s (%s, %d)",
s, d.String(),
d.value.String(), d.exp)
}
}
}
func TestNewFromInt32(t *testing.T) {
tests := map[int32]string{
0: "0",
1: "1",
323412345: "323412345",
2147483647: "2147483647",
}
// add negatives
for p, s := range tests {
if p > 0 {
tests[-p] = "-" + s
}
}
for input, s := range tests {
d := NewFromInt32(input)
if d.String() != s {
t.Errorf("expected %s, got %s (%s, %d)",
s, d.String(),
d.value.String(), d.exp)
}
}
}
func TestNewFromBigIntWithExponent(t *testing.T) { func TestNewFromBigIntWithExponent(t *testing.T) {
type Inp struct { type Inp struct {
val *big.Int val *big.Int