diff --git a/internal/helper/type_float.go b/internal/helper/type_float.go index e08e38ee..a841897f 100644 --- a/internal/helper/type_float.go +++ b/internal/helper/type_float.go @@ -1,6 +1,16 @@ package helper -// converts a floating point percentage to a parts per million value +import ( + "fmt" +) + +// FloatToPPM converts a floating point percentage to a parts per million value func FloatToPPM(f float64) int { return int(f * 10000) } + +// FloatToPercentString converts a floating point percentage to a string, with a maximum of +// 4 decimal places, no trailing zeros +func FloatToPercentString(f float64) string { + return fmt.Sprintf("%g", f) +} diff --git a/internal/helper/type_float_test.go b/internal/helper/type_float_test.go index 6a8dc444..9960a9a0 100644 --- a/internal/helper/type_float_test.go +++ b/internal/helper/type_float_test.go @@ -22,8 +22,29 @@ func TestTypeFloat_FloatToPPM(t *testing.T) { {input: 0.0001, expected: 1}, } for _, testCase := range testCases { - t.Run(fmt.Sprintf("returns correct value for input %f", testCase.input), func(t *testing.T) { + t.Run(fmt.Sprintf("returns correct value for input %g", testCase.input), func(t *testing.T) { assert.Equal(t, testCase.expected, FloatToPPM(testCase.input)) }) } } + +func TestTypeFloat_FloatToPercentString(t *testing.T) { + testCases := []struct { + input float64 + expected string + }{ + {input: 100, expected: "100"}, + {input: 99.00, expected: "99.00"}, + {input: 9.9999, expected: "9.9999"}, + {input: 9, expected: "9"}, + {input: 0.1, expected: "0.1"}, + {input: 0.01, expected: "0.01"}, + {input: 0.001, expected: "0.001"}, + {input: 0.0001, expected: "0.0001"}, + } + for _, testCase := range testCases { + t.Run(fmt.Sprintf("returns correct value for input %g", testCase.input), func(t *testing.T) { + assert.Equal(t, testCase.expected, FloatToPercentString(testCase.input)) + }) + } +}