Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions numeric.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,13 @@ func round(a interface{}, p int, rOpt ...float64) float64 {
var round float64
pow := math.Pow(10, places)
digit := pow * val
// Modf keeps the sign of the fraction. A negative fraction below the
// threshold rounds toward zero, matching the positive side.
_, div := math.Modf(digit)
if div >= roundOn {
round = math.Ceil(digit)
} else if div < 0 && div > -roundOn {
round = math.Ceil(digit)
} else {
round = math.Floor(digit)
}
Expand Down
9 changes: 9 additions & 0 deletions numeric_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,15 @@ func TestRound(t *testing.T) {
assert.Equal(t, 123.0, round(123.49999999, 0))
assert.Equal(t, 123.23, round(123.2329999, 2, .3))
assert.Equal(t, 123.24, round(123.233, 2, .3))
// A negative fraction below the threshold rounds toward zero.
// -1.25 is exact in float64. Floor would return -2.
assert.Equal(t, -1.0, round(-1.25, 0))
assert.Equal(t, -2.0, round(-1.5, 0))
assert.Equal(t, -2.0, round(-1.75, 0))
assert.Equal(t, -123.0, round(-123.49999999, 0))
assert.Equal(t, -124.0, round(-123.500001, 0))
assert.Equal(t, -123.23, round(-123.2329999, 2, .3))
assert.Equal(t, -123.24, round(-123.233, 2, .3))
}

func TestRandomInt(t *testing.T) {
Expand Down