Bug fix in RoundFloat func in common/math package (#579)

* refactored RoundFloat func in common/math package

* cleanup

Co-authored-by: Vazha Bezhanishvili <vazha.bezhanishvili@elegro.eu>
This commit is contained in:
Vazha
2020-10-16 02:13:10 +03:00
committed by GitHub
parent 8c86aac21d
commit 9945216cac
3 changed files with 32 additions and 25 deletions

View File

@@ -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
}

View File

@@ -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)
}
}
}
}

1
go.sum
View File

@@ -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=