From 10dbda7986c7768cd7bb089b3403aa14aadb222c Mon Sep 17 00:00:00 2001 From: NunoSempere Date: Sun, 30 Jun 2024 09:19:20 -0400 Subject: [PATCH] start parsing K, M, B, T suffixes --- pretty/pretty.go | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/pretty/pretty.go b/pretty/pretty.go index be74d12..1454d13 100644 --- a/pretty/pretty.go +++ b/pretty/pretty.go @@ -1,8 +1,10 @@ package pretty import ( + "errors" "fmt" "math" + "strconv" ) func PrettyPrintInt(n int) { @@ -49,3 +51,40 @@ func PrettyPrint2Floats(low float64, high float64) { fmt.Printf(" ") 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) + } + +}