From 286480b1fbb46cbbe80e930285e70353b5df8205 Mon Sep 17 00:00:00 2001 From: Karel Bilek Date: Mon, 23 Mar 2020 19:20:14 +0700 Subject: [PATCH] Add helper function to round to big.Int --- round.go | 13 +++++++++++++ round_test.go | 16 ++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/round.go b/round.go index d0df89f..0fccd1f 100644 --- a/round.go +++ b/round.go @@ -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() +} diff --git a/round_test.go b/round_test.go index af2f800..8ffbf66 100644 --- a/round_test.go +++ b/round_test.go @@ -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) {