优化小数格式化

This commit is contained in:
GoEdgeLab
2022-10-22 10:22:45 +08:00
parent 885b59eb15
commit 9a455aacd0
2 changed files with 16 additions and 9 deletions

View File

@@ -1,7 +1,10 @@
package numberutils
import (
"fmt"
"github.com/iwind/TeaGo/types"
"strconv"
"strings"
)
func FormatInt64(value int64) string {
@@ -43,18 +46,19 @@ func Min[T int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 |
}
func FloorFloat32(f float32, decimal int) float32 {
if decimal < 0 {
decimal = 0
if decimal <= 0 {
return f
}
for i := 0; i < decimal; i++ {
f *= 10
var s = fmt.Sprintf("%f", f)
var index = strings.Index(s, ".")
if index < 0 {
return f
}
f = float32(int64(f))
for i := 0; i < decimal; i++ {
f /= 10
var d = s[index:]
if len(d) <= decimal+1 {
return f
}
return f
return types.Float32(s[:index] + d[:decimal+1])
}

View File

@@ -27,8 +27,11 @@ func TestMaxFloat32(t *testing.T) {
func TestFloorFloat32(t *testing.T) {
t.Logf("%f", numberutils.FloorFloat32(123.456, -1))
t.Logf("%f", numberutils.FloorFloat32(123.456, 0))
t.Logf("%f", numberutils.FloorFloat32(123, 2))
t.Logf("%f, %f", numberutils.FloorFloat32(123.456, 1), 123.456*10)
t.Logf("%f, %f", numberutils.FloorFloat32(123.456, 2), 123.456*10*10)
t.Logf("%f, %f", numberutils.FloorFloat32(123.456, 3), 123.456*10*10*10)
t.Logf("%f, %f", numberutils.FloorFloat32(123.456, 4), 123.456*10*10*10*10)
t.Logf("%f, %f", numberutils.FloorFloat32(123.456789, 4), 123.456789*10*10*10*10)
t.Logf("%f", numberutils.FloorFloat32(-123.45678, 2))
}