add FormatNumber
This commit is contained in:
@@ -1,11 +1,50 @@
|
||||
package proxmoxaas_common_lib
|
||||
|
||||
const KiB = 1024
|
||||
const MiB = KiB * 1024
|
||||
const GiB = MiB * 1024
|
||||
const TiB = GiB * 1024
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const KB = 1000
|
||||
const MB = KB * 1000
|
||||
const GB = MB * 1000
|
||||
const TB = GB * 1000
|
||||
const Base1000 int64 = 1000
|
||||
const Base1024 int64 = 1024
|
||||
|
||||
var prefixesBase1000 []string = []string{"", "K", "M", "G", "T"}
|
||||
var prefixesBase1024 []string = []string{"", "Ki", "Mi", "Gi", "Ti"}
|
||||
|
||||
const KB int64 = Base1000
|
||||
const MB int64 = KB * Base1000
|
||||
const GB int64 = MB * Base1000
|
||||
const TB int64 = GB * Base1000
|
||||
|
||||
const KiB int64 = Base1024
|
||||
const MiB int64 = KiB * Base1024
|
||||
const GiB int64 = MiB * Base1024
|
||||
const TiB int64 = GiB * Base1024
|
||||
|
||||
func FormatNumber(val int64, base int64) (string, string) {
|
||||
valf := float64(val)
|
||||
basef := float64(base)
|
||||
steps := 0
|
||||
for math.Abs(valf) > basef && steps < 4 {
|
||||
valf /= basef
|
||||
steps++
|
||||
}
|
||||
|
||||
switch base {
|
||||
case Base1000:
|
||||
s := fmt.Sprintf("%.4f", valf)
|
||||
s = strings.TrimRight(s, "0")
|
||||
s = strings.TrimRight(s, ".")
|
||||
prefixes := prefixesBase1000
|
||||
return s, prefixes[steps]
|
||||
case Base1024:
|
||||
s := fmt.Sprintf("%.4f", valf)
|
||||
s = strings.TrimRight(s, "0")
|
||||
s = strings.TrimRight(s, ".")
|
||||
prefixes := prefixesBase1024
|
||||
return s, prefixes[steps]
|
||||
default:
|
||||
return "0", ""
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user