1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

refactor(mathutil): round related method support generics (#195)

This commit is contained in:
Cannian
2024-03-01 16:04:23 +08:00
committed by GitHub
parent 81d13c2f1a
commit c02c4f813b
4 changed files with 24 additions and 18 deletions

View File

@@ -68,26 +68,26 @@ func Percent(val, total float64, n int) float64 {
// RoundToString round up to n decimal places.
// Play: https://go.dev/play/p/kZwpBRAcllO
func RoundToString(x float64, n int) string {
func RoundToString[T constraints.Float | constraints.Integer](x T, n int) string {
tmp := math.Pow(10.0, float64(n))
x *= tmp
x = math.Round(x)
result := strconv.FormatFloat(x/tmp, 'f', n, 64)
x *= T(tmp)
r := math.Round(float64(x))
result := strconv.FormatFloat(r/tmp, 'f', n, 64)
return result
}
// RoundToFloat round up to n decimal places.
// Play: https://go.dev/play/p/ghyb528JRJL
func RoundToFloat(x float64, n int) float64 {
func RoundToFloat[T constraints.Float | constraints.Integer](x T, n int) float64 {
tmp := math.Pow(10.0, float64(n))
x *= tmp
x = math.Round(x)
return x / tmp
x *= T(tmp)
r := math.Round(float64(x))
return r / tmp
}
// TruncRound round off n decimal places.
// Play: https://go.dev/play/p/aumarSHIGzP
func TruncRound(x float64, n int) float64 {
func TruncRound[T constraints.Float | constraints.Integer](x T, n int) T {
floatStr := fmt.Sprintf("%."+strconv.Itoa(n+1)+"f", x)
temp := strings.Split(floatStr, ".")
var newFloat string
@@ -97,7 +97,7 @@ func TruncRound(x float64, n int) float64 {
newFloat = temp[0] + "." + temp[1][:n]
}
result, _ := strconv.ParseFloat(newFloat, 64)
return result
return T(result)
}
// Max return max value of numbers.

View File

@@ -72,6 +72,8 @@ func TestRoundToString(t *testing.T) {
assert.Equal("0.12", RoundToString(0.124, 2))
assert.Equal("0.13", RoundToString(0.125, 2))
assert.Equal("0.125", RoundToString(0.125, 3))
//assert.Equal("54.321", RoundToString(54.321, 3))
//assert.Equal("17.000", RoundToString(17, 3))
}
func TestTruncRound(t *testing.T) {
@@ -79,8 +81,12 @@ func TestTruncRound(t *testing.T) {
assert := internal.NewAssert(t, "TestTruncRound")
assert.Equal(float64(0), TruncRound(0, 0))
assert.Equal(float64(0), TruncRound(0, 1))
assert.Equal(float64(0), TruncRound(float64(0), 0))
assert.Equal(float64(0), TruncRound(float64(0), 1))
assert.Equal(float32(0), TruncRound(float32(0), 0))
assert.Equal(float32(0), TruncRound(float32(0), 1))
assert.Equal(0, TruncRound(0, 0))
assert.Equal(uint64(0), TruncRound(uint64(0), 1))
assert.Equal(0.12, TruncRound(0.124, 2))
assert.Equal(0.12, TruncRound(0.125, 2))
assert.Equal(0.125, TruncRound(0.125, 3))