91 lines
2.1 KiB
Go
91 lines
2.1 KiB
Go
package pretty
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"strconv"
|
|
)
|
|
|
|
func PrettyPrintInt(n int) {
|
|
switch {
|
|
case math.Abs(float64(n)) >= 1_000_000_000_000:
|
|
fmt.Printf("%dT", n/1_000_000_000_000)
|
|
case math.Abs(float64(n)) >= 1_000_000_000:
|
|
fmt.Printf("%dB", n/1_000_000_000)
|
|
case math.Abs(float64(n)) >= 1_000_000:
|
|
fmt.Printf("%dM", n/1_000_000)
|
|
case math.Abs(float64(n)) >= 1_000:
|
|
fmt.Printf("%dK", n/1_000)
|
|
default:
|
|
fmt.Printf("%df", n)
|
|
}
|
|
}
|
|
|
|
func PrettyPrintFloat(f float64) {
|
|
switch {
|
|
case math.Abs(f) >= 1_000_000_000_000:
|
|
fmt.Printf("%.1fT", f/1_000_000_000_000)
|
|
case math.Abs(f) >= 1_000_000_000:
|
|
fmt.Printf("%.1fB", f/1_000_000_000)
|
|
case math.Abs(f) >= 1_000_000:
|
|
fmt.Printf("%.1fM", f/1_000_000)
|
|
case math.Abs(f) >= 1_000:
|
|
fmt.Printf("%.1fK", f/1_000)
|
|
|
|
case math.Abs(f) <= 0.0001:
|
|
fmt.Printf("%.5f", f)
|
|
case math.Abs(f) <= 0.001:
|
|
fmt.Printf("%.4f", f)
|
|
case math.Abs(f) <= 0.01:
|
|
fmt.Printf("%.3f", f)
|
|
case math.Abs(f) <= 0.1:
|
|
fmt.Printf("%.2f", f)
|
|
default:
|
|
fmt.Printf("%.1f", f)
|
|
}
|
|
|
|
}
|
|
func PrettyPrint2Floats(low float64, high float64) {
|
|
PrettyPrintFloat(low)
|
|
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)
|
|
}
|
|
|
|
}
|