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