start parsing K, M, B, T suffixes

This commit is contained in:
NunoSempere 2024-06-30 09:19:20 -04:00
parent 9dc6e1443d
commit 10dbda7986

View File

@ -1,8 +1,10 @@
package pretty package pretty
import ( import (
"errors"
"fmt" "fmt"
"math" "math"
"strconv"
) )
func PrettyPrintInt(n int) { func PrettyPrintInt(n int) {
@ -49,3 +51,40 @@ func PrettyPrint2Floats(low float64, high float64) {
fmt.Printf(" ") fmt.Printf(" ")
PrettyPrintFloat(high) PrettyPrintFloat(high)
} }
func multiplyOrPassThroughError(a float64, b float64, err error) (float64, error) {
if err != nil {
return b, err
} else {
return a * b, nil
}
}
func parseFloat(word string) (float64, error) {
// l = len(word) // assuming no UTF stuff
if len(word) == 0 {
return 0, errors.New("String to be parsed into float must not be the empty string")
} else if len(word) == 1 {
return strconv.ParseFloat(word)
}
n = len(word) - 1
switch word[n] {
case "K":
f, err := strconv.ParseFloat(word[:n], 64)
return multiplyOrPassThroughError(1_000, f, err)
case "M":
f, err := strconv.ParseFloat(word[:n], 64)
return multiplyOrPassThroughError(1_000_000, f, err)
case "B":
f, err := strconv.ParseFloat(word[:n], 64)
return multiplyOrPassThroughError(1_000_000_000, f, err)
case "T":
f, err := strconv.ParseFloat(word[:n], 64)
return multiplyOrPassThroughError(1_000_000_000, f, err)
default:
return strconv.ParseFloat(word)
}
}