Skip to content

Commit

Permalink
Added ToFixedCruncate
Browse files Browse the repository at this point in the history
  • Loading branch information
btm6084 committed May 22, 2023
1 parent e6751d0 commit 8b6eb70
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
8 changes: 7 additions & 1 deletion conv/conv.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,18 @@ func Round(num float64) int {
return int(num + math.Copysign(0.5, num))
}

// ToFixed will set a fixed precision on a float.
// ToFixed will set a fixed precision on a float. Rounded
func ToFixed(num float64, precision int) float64 {
output := math.Pow(10, float64(precision))
return float64(Round(num*output)) / output
}

// ToFixedTruncate will set a fixed precision on a float. Not rounded, just truncated
func ToFixedTruncate(num float64, precision int) float64 {
output := math.Pow(10, float64(precision))
return float64(int(num*output)) / output
}

func ZeroIfNilInt(in *int) int {
if in == nil {
return 0
Expand Down
9 changes: 9 additions & 0 deletions conv/conv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,15 @@ func TestToFixed(t *testing.T) {
require.Equal(t, 0.3, ToFixed(a+b, 1))
}

func TestToFixedTruncate(t *testing.T) {
require.Equal(t, 9.0, ToFixedTruncate(9.06514265000000007, 0))
require.Equal(t, 9.0, ToFixedTruncate(9.06514265000000007, 1))
require.Equal(t, 9.06, ToFixedTruncate(9.06514265000000007, 2))
require.Equal(t, 9.065, ToFixedTruncate(9.06514265000000007, 3))
require.Equal(t, 9.0651, ToFixedTruncate(9.06514265000000007, 4))
require.Equal(t, 9.06514, ToFixedTruncate(9.06514265000000007, 5))
}

func TestFormatDuration(t *testing.T) {
testCases := []struct {
Label string
Expand Down

0 comments on commit 8b6eb70

Please sign in to comment.