diff --git a/pkg/util/integer/integer.go b/pkg/util/integer/integer.go index c51cd952d1d..81e28cfbf49 100644 --- a/pkg/util/integer/integer.go +++ b/pkg/util/integer/integer.go @@ -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) +} diff --git a/pkg/util/integer/integer_test.go b/pkg/util/integer/integer_test.go index 0f885673827..2000a457058 100644 --- a/pkg/util/integer/integer_test.go +++ b/pkg/util/integer/integer_test.go @@ -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) + } + } +}