integer: add utility for proper integer rounding

This commit is contained in:
Michail Kargakis 2016-02-26 14:34:33 +01:00
parent 0730ffbff7
commit bad8b6dde4
2 changed files with 47 additions and 0 deletions

View File

@ -43,3 +43,11 @@ func Int64Min(a, b int64) int64 {
}
return a
}
// RoundToInt32 rounds floats into integer numbers.
func RoundToInt32(a float64) int32 {
if a < 0 {
return int32(a - 0.5)
}
return int32(a + 0.5)
}

View File

@ -141,3 +141,42 @@ func TestInt64Min(t *testing.T) {
}
}
}
func TestRoundToInt32(t *testing.T) {
tests := []struct {
num float64
exp int32
}{
{
num: 5.5,
exp: 6,
},
{
num: -3.7,
exp: -4,
},
{
num: 3.49,
exp: 3,
},
{
num: -7.9,
exp: -8,
},
{
num: -4.499999,
exp: -4,
},
{
num: 0,
exp: 0,
},
}
for i, test := range tests {
t.Logf("executing scenario %d", i)
if got := RoundToInt32(test.num); got != test.exp {
t.Errorf("expected %d, got %d", test.exp, got)
}
}
}