feat(numx): 自 go-hua/common 迁入数值工具并独立成包
- 流量格式化、低位取整、多整数取最值(Max/Min 自 version.go 归位) - 附单元测试、examples/numx 例程与包 README
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
// Package numx 数值处理与可读格式化工具:数字低位取整、流量字节数格式化、多整数取最值。
|
||||
package numx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
)
|
||||
|
||||
// IgnoreDigits 数字低位取整:去掉最后 digitsToIgnore 位并补零
|
||||
func IgnoreDigits(value, digitsToIgnore int) int {
|
||||
divider := int(math.Pow10(digitsToIgnore))
|
||||
return (value / divider) * divider
|
||||
}
|
||||
|
||||
// FormatFlow 流量字节数格式化为带单位的可读字符串(B/KB/MB/GB/TB)
|
||||
func FormatFlow(value int64) string {
|
||||
if value < 1024 {
|
||||
return fmt.Sprintf("%d B", value)
|
||||
} else if value < 1024*1024 {
|
||||
return fmt.Sprintf("%.1f KB", float64(value)/float64(1024))
|
||||
} else if value < 1024*1024*1024 {
|
||||
return fmt.Sprintf("%.1f MB", float64(value)/float64(1024*1024))
|
||||
} else if value < 1024*1024*1024*1024 {
|
||||
return fmt.Sprintf("%.1f GB", float64(value)/float64(1024*1024*1024))
|
||||
}
|
||||
return fmt.Sprintf("%.2f TB", float64(value)/float64(1024*1024*1024*1024))
|
||||
}
|
||||
|
||||
// Max 返回多个整数中的最大值
|
||||
func Max(vals ...int) int {
|
||||
var max int
|
||||
for _, val := range vals {
|
||||
if val > max {
|
||||
max = val
|
||||
}
|
||||
}
|
||||
return max
|
||||
}
|
||||
|
||||
// Min 返回多个整数中的最小值
|
||||
func Min(vals ...int) int {
|
||||
var min int
|
||||
for _, val := range vals {
|
||||
if min == 0 || val <= min {
|
||||
min = val
|
||||
}
|
||||
}
|
||||
return min
|
||||
}
|
||||
Reference in New Issue
Block a user