mirror of
https://github.com/TeaOSLab/EdgeAPI.git
synced 2025-11-03 15:00:27 +08:00
提升小数数字精度
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"github.com/iwind/TeaGo/types"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func FormatInt64(value int64) string {
|
||||
@@ -44,10 +45,16 @@ func Min[T int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 |
|
||||
return min
|
||||
}
|
||||
|
||||
func FloorFloat32(f float32, decimal int) float32 {
|
||||
func FloorFloat64(f float64, decimal int) float64 {
|
||||
if decimal <= 0 {
|
||||
return f
|
||||
}
|
||||
|
||||
return types.Float32(fmt.Sprintf("%.2f", f))
|
||||
var s = fmt.Sprintf("%f", f)
|
||||
var index = strings.Index(s, ".")
|
||||
if index < 0 || len(s[index:]) <= decimal+1 {
|
||||
return f
|
||||
}
|
||||
|
||||
return types.Float64(s[:index+decimal+1])
|
||||
}
|
||||
|
||||
@@ -24,20 +24,20 @@ func TestMaxFloat32(t *testing.T) {
|
||||
t.Logf("%f", math.MaxFloat32/(1<<100))
|
||||
}
|
||||
|
||||
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))
|
||||
func TestFloorFloat64(t *testing.T) {
|
||||
t.Logf("%f", numberutils.FloorFloat64(123.456, -1))
|
||||
t.Logf("%f", numberutils.FloorFloat64(123.456, 0))
|
||||
t.Logf("%f", numberutils.FloorFloat64(123, 2))
|
||||
t.Logf("%f, %f", numberutils.FloorFloat64(123.456, 1), 123.456*10)
|
||||
t.Logf("%f, %f", numberutils.FloorFloat64(123.456, 2), 123.456*10*10)
|
||||
t.Logf("%f, %f", numberutils.FloorFloat64(123.456, 3), 123.456*10*10*10)
|
||||
t.Logf("%f, %f", numberutils.FloorFloat64(123.456, 4), 123.456*10*10*10*10)
|
||||
t.Logf("%f, %f", numberutils.FloorFloat64(123.456789, 4), 123.456789*10*10*10*10)
|
||||
t.Logf("%f", numberutils.FloorFloat64(-123.45678, 2))
|
||||
}
|
||||
|
||||
func TestFloorFloat32_Special(t *testing.T) {
|
||||
for _, f := range []float32{17.88, 1.11, 1.23456} {
|
||||
t.Logf("%f", numberutils.FloorFloat32(f, 2))
|
||||
func TestFloorFloat64_Special(t *testing.T) {
|
||||
for _, f := range []float64{17.88, 1.11, 1.23456} {
|
||||
t.Logf("%f", numberutils.FloorFloat64(f, 2))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user