diff --git a/number/number.go b/number/number.go new file mode 100644 index 0000000..f616e8a --- /dev/null +++ b/number/number.go @@ -0,0 +1,10 @@ +package number + +import "math" + +func IsWhole(num float64) bool { + if math.IsInf(num, 0) || math.IsNaN(num) { + return false + } + return math.Trunc(num) == num +} diff --git a/number/number_test.go b/number/number_test.go new file mode 100644 index 0000000..9fe226b --- /dev/null +++ b/number/number_test.go @@ -0,0 +1,61 @@ +package number + +import ( + "fmt" + "math" + "testing" +) + +func TestIsWhole(t *testing.T) { + tests := []struct { + input float64 + expected bool + }{ + { + input: 0.000, + expected: true, + }, + { + input: 2.90, + expected: false, + }, + { + input: 1.9, + expected: false, + }, + { + input: 1, + expected: true, + }, + { + input: 0.11, + expected: false, + }, + { + input: -0.11, + expected: false, + }, + { + input: -1, + expected: true, + }, + { + input: math.Inf(-1), + expected: false, + }, + { + input: math.Inf(1), + expected: false, + }, + } + + for _, test := range tests { + t.Run(fmt.Sprintf("test isWholeNumber for %f", test.input), func(t *testing.T) { + resp := IsWhole(test.input) + + if resp != test.expected { + t.Errorf("unexpected result %v", resp) + } + }) + } +}