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
13 changes: 13 additions & 0 deletions round.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,16 @@ func Round(x *big.Rat, prec int, method RoundingMode) *big.Rat {
// To force renormalization
return x.SetFrac(n, d)
}

// RoundToInt returns x, rounded as integer. Does not modify x
func RoundToInt(x *big.Rat, method RoundingMode) *big.Int {
c := new(big.Rat).Set(x)
Round(c, 0, method)

if !c.IsInt() {
panic("unexpected unrounded rational")
}

// as c is int, denominator is 1 and numerator is the int value
return c.Num()
}
16 changes: 16 additions & 0 deletions round_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,22 @@ func testRounding(t *testing.T, a, b string, prec int, method RoundingMode) {
if x.Cmp(y) != 0 {
t.Errorf("test Round(%v, %v, %v) == %s. Got %v", a, prec, method, y.FloatString(3), x.FloatString(3))
}

if prec == 0 {
x, ok := new(big.Rat).SetString(a)
if !ok {
t.Fatalf("Failed to parse: %s", b)
}

yInt, ok := new(big.Int).SetString(b, 10)
if !ok {
t.Fatalf("Failed to parse: %s", b)
}
xRounded := RoundToInt(x, method)
if xRounded.Cmp(yInt) != 0 {
t.Errorf("test RoundToInt(%v, %v) == %s. Got %v", a, method, yInt, xRounded)
}
}
}

func BenchmarkRoundUp(b *testing.B) {
Expand Down