Skip to content

Commit

Permalink
add Truncate: returns the float32/float64 of the specified precision
Browse files Browse the repository at this point in the history
  • Loading branch information
freeeverett committed Sep 18, 2024
1 parent f3c9134 commit 86ec52e
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
16 changes: 16 additions & 0 deletions math.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,19 @@ func Round[T float64 | float32](f T, n ...int) T {
pow10N := math.Pow10(nn)
return T(math.Round(float64(f)*pow10N) / pow10N)
}

// Truncate returns the float32/float64 of the specified precision
func Truncate[T float64 | float32](f T, n ...int) T {
var nn = 3
if len(n) > 0 {
nnn := n[0]
if nnn >= 0 {
nn = nnn
if nn > 15 {
nn = 15
}
}
}
pow10N := math.Pow10(nn)
return T(math.Floor(float64(f)*pow10N) / pow10N)
}
17 changes: 17 additions & 0 deletions math_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,20 @@ func ExampleRound() {
// 1.235
// 1.23456
}

func ExampleTruncate() {
result1 := Truncate(1.23456)
result2 := Truncate(1.23456, 2)
result3 := Truncate(1.23456, 4)
result4 := Truncate(1.23456, 7)

fmt.Printf("%v\n", result1)
fmt.Printf("%v\n", result2)
fmt.Printf("%v\n", result3)
fmt.Printf("%v\n", result4)
// Output:
// 1.234
// 1.23
// 1.2345
// 1.23456
}
25 changes: 25 additions & 0 deletions math_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,28 @@ func TestRound(t *testing.T) {
is.Equal(result8, 1.0)
is.Equal(result9, 1.0)
}

func TestTruncate(t *testing.T) {
t.Parallel()
is := assert.New(t)

result1 := Truncate(0.086990000031, 5)
result2 := Truncate(1.23456)
result3 := Truncate(1.23456, 2)
result4 := Truncate(1.23456, 3)
result5 := Truncate(1.23456, 7)
result6 := Truncate(1.23456, 16)
result7 := Truncate(1.23456, -1)
result8 := Truncate(1.23456, 0)
result9 := Truncate(1.00000000001, 5)

is.Equal(result1, 0.08699)
is.Equal(result2, 1.234)
is.Equal(result3, 1.23)
is.Equal(result4, 1.234)
is.Equal(result5, 1.23456)
is.Equal(result6, 1.23456)
is.Equal(result7, 1.234)
is.Equal(result8, 1.0)
is.Equal(result9, 1.0)
}

0 comments on commit 86ec52e

Please sign in to comment.