mirror of
https://github.com/k3s-io/kubernetes.git
synced 2025-07-31 07:20:13 +00:00
integer: add utility for proper integer rounding
This commit is contained in:
parent
0730ffbff7
commit
bad8b6dde4
@ -43,3 +43,11 @@ func Int64Min(a, b int64) int64 {
|
|||||||
}
|
}
|
||||||
return a
|
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)
|
||||||
|
}
|
||||||
|
@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user