优化小数格式化

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 package numberutils
import ( import (
"fmt"
"github.com/iwind/TeaGo/types"
"strconv" "strconv"
"strings"
) )
func FormatInt64(value int64) string { 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 { func FloorFloat32(f float32, decimal int) float32 {
if decimal < 0 { if decimal <= 0 {
decimal = 0 return f
} }
for i := 0; i < decimal; i++ { var s = fmt.Sprintf("%f", f)
f *= 10 var index = strings.Index(s, ".")
if index < 0 {
return f
} }
f = float32(int64(f)) var d = s[index:]
if len(d) <= decimal+1 {
for i := 0; i < decimal; i++ { return f
f /= 10
} }
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) { func TestFloorFloat32(t *testing.T) {
t.Logf("%f", numberutils.FloorFloat32(123.456, -1)) t.Logf("%f", numberutils.FloorFloat32(123.456, -1))
t.Logf("%f", numberutils.FloorFloat32(123.456, 0)) 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, 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, 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, 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.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))
} }