mirror of
https://github.com/TeaOSLab/EdgeAPI.git
synced 2025-11-11 04:50:25 +08:00
优化小数格式化
This commit is contained in:
@@ -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
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < decimal; i++ {
|
|
||||||
f *= 10
|
|
||||||
}
|
|
||||||
|
|
||||||
f = float32(int64(f))
|
|
||||||
|
|
||||||
for i := 0; i < decimal; i++ {
|
|
||||||
f /= 10
|
|
||||||
}
|
|
||||||
return f
|
return f
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var s = fmt.Sprintf("%f", f)
|
||||||
|
var index = strings.Index(s, ".")
|
||||||
|
if index < 0 {
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
var d = s[index:]
|
||||||
|
if len(d) <= decimal+1 {
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
return types.Float32(s[:index] + d[:decimal+1])
|
||||||
|
}
|
||||||
|
|||||||
@@ -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))
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user