gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

ftoa.go (986B)


      1 package humanize
      2 
      3 import (
      4 	"strconv"
      5 	"strings"
      6 )
      7 
      8 func stripTrailingZeros(s string) string {
      9 	if !strings.ContainsRune(s, '.') {
     10 		return s
     11 	}
     12 	offset := len(s) - 1
     13 	for offset > 0 {
     14 		if s[offset] == '.' {
     15 			offset--
     16 			break
     17 		}
     18 		if s[offset] != '0' {
     19 			break
     20 		}
     21 		offset--
     22 	}
     23 	return s[:offset+1]
     24 }
     25 
     26 func stripTrailingDigits(s string, digits int) string {
     27 	if i := strings.Index(s, "."); i >= 0 {
     28 		if digits <= 0 {
     29 			return s[:i]
     30 		}
     31 		i++
     32 		if i+digits >= len(s) {
     33 			return s
     34 		}
     35 		return s[:i+digits]
     36 	}
     37 	return s
     38 }
     39 
     40 // Ftoa converts a float to a string with no trailing zeros.
     41 func Ftoa(num float64) string {
     42 	return stripTrailingZeros(strconv.FormatFloat(num, 'f', 6, 64))
     43 }
     44 
     45 // FtoaWithDigits converts a float to a string but limits the resulting string
     46 // to the given number of decimal places, and no trailing zeros.
     47 func FtoaWithDigits(num float64, digits int) string {
     48 	return stripTrailingZeros(stripTrailingDigits(strconv.FormatFloat(num, 'f', 6, 64), digits))
     49 }