Compare commits
3 Commits
372fd452c7
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 24904dde66 | |||
| d6173c8675 | |||
| 41a06f6b45 |
@@ -2,6 +2,7 @@ package proxmoxaas_common_lib
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"math"
|
"math"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
@@ -23,28 +24,34 @@ const GiB uint64 = MiB * Base1024
|
|||||||
const TiB uint64 = GiB * Base1024
|
const TiB uint64 = GiB * Base1024
|
||||||
|
|
||||||
func FormatNumber(val uint64, base uint64) (string, string) {
|
func FormatNumber(val uint64, base uint64) (string, string) {
|
||||||
|
prefixes := []string{""}
|
||||||
|
switch base {
|
||||||
|
case Base1000:
|
||||||
|
prefixes = prefixesBase1000
|
||||||
|
case Base1024:
|
||||||
|
prefixes = prefixesBase1024
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
valf := float64(val)
|
valf := float64(val)
|
||||||
basef := float64(base)
|
basef := float64(base)
|
||||||
steps := 0
|
steps := 0
|
||||||
for math.Abs(valf) > basef && steps < 4 {
|
for math.Abs(valf) > basef && steps < len(prefixes)-1 {
|
||||||
valf /= basef
|
valf /= basef
|
||||||
steps++
|
steps++
|
||||||
}
|
}
|
||||||
|
|
||||||
switch base {
|
|
||||||
case Base1000:
|
|
||||||
s := fmt.Sprintf("%.4f", valf)
|
s := fmt.Sprintf("%.4f", valf)
|
||||||
s = strings.TrimRight(s, "0")
|
s = strings.TrimRight(s, "0")
|
||||||
s = strings.TrimRight(s, ".")
|
s = strings.TrimRight(s, ".")
|
||||||
prefixes := prefixesBase1000
|
|
||||||
return s, prefixes[steps]
|
return s, prefixes[steps]
|
||||||
case Base1024:
|
}
|
||||||
s := fmt.Sprintf("%.4f", valf)
|
|
||||||
s = strings.TrimRight(s, "0")
|
// Converts int, int32, and int64 to uint64. Less than 0 check.
|
||||||
s = strings.TrimRight(s, ".")
|
func SafeUint64[I int | int32 | int64](i I) uint64 {
|
||||||
prefixes := prefixesBase1024
|
if i < 0 {
|
||||||
return s, prefixes[steps]
|
log.Printf("Tried to cast %d to uint64", i)
|
||||||
default:
|
return 0
|
||||||
return "0", ""
|
}
|
||||||
}
|
return uint64(i)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user