mirror of
https://github.com/shopspring/decimal.git
synced 2024-11-22 20:40:48 +01:00
parent
ff9ed33395
commit
bc70c3beb9
3 changed files with 77 additions and 1 deletions
|
@ -34,7 +34,7 @@ func main() {
|
|||
panic(err)
|
||||
}
|
||||
|
||||
quantity := decimal.NewFromFloat(3)
|
||||
quantity := decimal.NewFromInt(3)
|
||||
|
||||
fee, _ := decimal.NewFromString(".035")
|
||||
taxRate, _ := decimal.NewFromString(".08875")
|
||||
|
|
26
decimal.go
26
decimal.go
|
@ -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
|
||||
func NewFromBigInt(value *big.Int, exp int32) Decimal {
|
||||
return Decimal{
|
||||
|
|
|
@ -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) {
|
||||
type Inp struct {
|
||||
val *big.Int
|
||||
|
|
Loading…
Reference in a new issue