diff --git a/common/math/math.go b/common/math/math.go index fccd6e72..406a86bf 100644 --- a/common/math/math.go +++ b/common/math/math.go @@ -31,21 +31,6 @@ func CalculateNetProfit(amount, priceThen, priceNow, costs float64) float64 { // RoundFloat rounds your floating point number to the desired decimal place func RoundFloat(x float64, prec int) float64 { - var rounder float64 pow := math.Pow(10, float64(prec)) - intermed := x * pow - _, frac := math.Modf(intermed) - intermed += .5 - x = .5 - if frac < 0.0 { - x = -.5 - intermed-- - } - if frac >= x { - rounder = math.Ceil(intermed) - } else { - rounder = math.Floor(intermed) - } - - return rounder / pow + return math.Round(x*pow) / pow } diff --git a/common/math/math_test.go b/common/math/math_test.go index 37de7cdf..f0e4fd17 100644 --- a/common/math/math_test.go +++ b/common/math/math_test.go @@ -66,16 +66,37 @@ func TestCalculateNetProfit(t *testing.T) { func TestRoundFloat(t *testing.T) { t.Parallel() - // mapping of input vs expected result - testTable := map[float64]float64{ - 2.3232323: 2.32, - -2.3232323: -2.32, + // mapping of input vs expected result : map[precision]map[testedValue]expectedOutput + testTableValues := map[int]map[float64]float64{ + 0: { + 2.23456789: 2, + -2.23456789: -2, + }, + 1: { + 2.23456789: 2.2, + -2.23456789: -2.2, + }, + 2: { + 2.23456789: 2.23, + -2.23456789: -2.23, + }, + 4: { + 2.23456789: 2.2346, + -2.23456789: -2.2346, + }, + 8: { + 2.23456781: 2.23456781, + -2.23456781: -2.23456781, + }, } - for testInput, expectedOutput := range testTable { - actualOutput := RoundFloat(testInput, 2) - if actualOutput != expectedOutput { - t.Errorf("RoundFloat Expected '%f'. Actual '%f'.", - expectedOutput, actualOutput) + + for precision, values := range testTableValues { + for testInput, expectedOutput := range values { + actualOutput := RoundFloat(testInput, precision) + if actualOutput != expectedOutput { + t.Errorf("RoundFloat Expected '%v'. Actual '%v' on precission %d", + expectedOutput, actualOutput, precision) + } } } } diff --git a/go.sum b/go.sum index 3f669fb9..ef4ffeb4 100644 --- a/go.sum +++ b/go.sum @@ -649,6 +649,7 @@ google.golang.org/grpc v1.31.0 h1:T7P4R73V3SSDPhH7WW7ATbfViLtmamH0DKrP3f9AuDI= google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.32.0 h1:zWTV+LMdc3kaiJMSTOFz2UgSBgx8RNQoTGiZu3fR9S0= google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.33.0 h1:IBKSUNL2uBS2DkJBncPP+TwT0sp9tgA8A75NjHt6umg= google.golang.org/grpc v1.33.0/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/grpc/examples v0.0.0-20200825214159-c4ba4cc6af4a h1:LwiilwqlW063bWAVbMG6G57sv7YyPZX3N0X298jj1nA= google.golang.org/grpc/examples v0.0.0-20200825214159-c4ba4cc6af4a/go.mod h1:Lh55/1hxmVHEkOvSIQ2uj0P12QyOCUNyRwnUlSS13hw=