chore: refactor structure
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
package number
|
||||
|
||||
import "math"
|
||||
|
||||
func Fixed3(num float64) float64 {
|
||||
return fixed(num, 3)
|
||||
}
|
||||
|
||||
func fixed(num float64, precision int) float64 {
|
||||
output := math.Pow(10, float64(precision))
|
||||
return float64(round(num*output)) / output
|
||||
}
|
||||
|
||||
func round(num float64) int {
|
||||
return int(num + math.Copysign(0.5, num))
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package number
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestFixed(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
precision int
|
||||
source, expected float64
|
||||
}{
|
||||
{3, 0, 0},
|
||||
{3, -1, -1},
|
||||
{3, 1.5, 1.5},
|
||||
{3, 2.25, 2.25},
|
||||
{3, 3.275, 3.275},
|
||||
{3, 4.0004, 4.000},
|
||||
{5, 5.000005, 5.00001},
|
||||
{4, -6.00004, -6.},
|
||||
{4, -6.00005, -6.0001},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("%f", tc.source), func(t *testing.T) {
|
||||
if tc.precision == 3 {
|
||||
assert.Equal(t, tc.expected, Fixed3(tc.source))
|
||||
} else {
|
||||
assert.Equal(t, tc.expected, fixed(tc.source, tc.precision))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user