Skip to content

Commit

Permalink
Must be rouned up when making Decimal from float
Browse files Browse the repository at this point in the history
  • Loading branch information
suminb committed Apr 16, 2019
1 parent 659d0b2 commit 35d9e08
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
4 changes: 3 additions & 1 deletion goport/src/finance/decimal.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package finance

import "math"

// Decimal is a fixed-point type with four decimal points
type Decimal int64

Expand All @@ -14,7 +16,7 @@ func DecimalFromString(value string) Decimal {
}

func DecimalFromFloat(value float64) Decimal {
return Decimal(value * DecimalMultiplier)
return Decimal(math.Round(value * DecimalMultiplier))
}

func (d Decimal) Floor() int64 {
Expand Down
15 changes: 15 additions & 0 deletions goport/src/finance/decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,18 @@ func TestDecimalFloor(t *testing.T) {
assertEquals(t, param.expected, actual, "Incorrect value")
}
}

func TestDecimalArithmatics(t *testing.T) {
params := []struct {
x float64
y float64
expected float64
}{
{3.78, 12.3, 16.08},
}
for _, param := range params {
x := DecimalFromFloat(param.x)
y := DecimalFromFloat(param.y)
assertEquals(t, DecimalFromFloat(param.expected), x+y, "Incorrect value")
}
}

0 comments on commit 35d9e08

Please sign in to comment.