fermi

A minimalist calculator for estimating with distributions
Log | Files | Refs | README

pretty.go (1968B)


      1 package pretty
      2 
      3 import (
      4 	"errors"
      5 	"fmt"
      6 	"math"
      7 	"strconv"
      8 )
      9 
     10 func PrettyPrintInt(n int) {
     11 	switch {
     12 	case math.Abs(float64(n)) >= 1_000_000_000_000:
     13 		fmt.Printf("%dT", n/1_000_000_000_000)
     14 	case math.Abs(float64(n)) >= 1_000_000_000:
     15 		fmt.Printf("%dB", n/1_000_000_000)
     16 	case math.Abs(float64(n)) >= 1_000_000:
     17 		fmt.Printf("%dM", n/1_000_000)
     18 	case math.Abs(float64(n)) >= 1_000:
     19 		fmt.Printf("%dK", n/1_000)
     20 	default:
     21 		fmt.Printf("%df", n)
     22 	}
     23 }
     24 
     25 func PrettyPrintFloat(f float64) {
     26 	switch {
     27 	case math.Abs(f) >= 1_000_000_000_000:
     28 		fmt.Printf("%.1fT", f/1_000_000_000_000)
     29 	case math.Abs(f) >= 1_000_000_000:
     30 		fmt.Printf("%.1fB", f/1_000_000_000)
     31 	case math.Abs(f) >= 1_000_000:
     32 		fmt.Printf("%.1fM", f/1_000_000)
     33 	case math.Abs(f) >= 1_000:
     34 		fmt.Printf("%.1fK", f/1_000)
     35 
     36 	case math.Abs(f) <= 0.0001:
     37 		fmt.Printf("%.5f", f)
     38 	case math.Abs(f) <= 0.001:
     39 		fmt.Printf("%.4f", f)
     40 	case math.Abs(f) <= 0.01:
     41 		fmt.Printf("%.3f", f)
     42 	case math.Abs(f) <= 0.1:
     43 		fmt.Printf("%.2f", f)
     44 	default:
     45 		fmt.Printf("%.1f", f)
     46 	}
     47 
     48 }
     49 func PrettyPrint2Floats(low float64, high float64) {
     50 	PrettyPrintFloat(low)
     51 	fmt.Printf(" ")
     52 	PrettyPrintFloat(high)
     53 }
     54 
     55 func multiplyOrPassThroughError(a float64, b float64, err error) (float64, error) {
     56 	if err != nil {
     57 		return b, err
     58 	} else {
     59 		return a * b, nil
     60 	}
     61 }
     62 
     63 func ParseFloat(word string) (float64, error) {
     64 	// l = len(word) // assuming no UTF stuff
     65 	switch len(word) {
     66 	case 0:
     67 		return 0, errors.New("String to be parsed into float must not be the empty string")
     68 	case 1:
     69 		return strconv.ParseFloat(word, 64)
     70 	}
     71 
     72 	n := len(word) - 1
     73 	f, err := strconv.ParseFloat(word[:n], 64)
     74 	switch word[n] {
     75 	case 'K':
     76 		return multiplyOrPassThroughError(1_000, f, err)
     77 	case 'M':
     78 		return multiplyOrPassThroughError(1_000_000, f, err)
     79 	case 'B':
     80 		return multiplyOrPassThroughError(1_000_000_000, f, err)
     81 	case 'T':
     82 		return multiplyOrPassThroughError(1_000_000_000_000, f, err)
     83 	default:
     84 		return strconv.ParseFloat(word, 64)
     85 	}
     86 
     87 }