Quantcast
Channel: User Sergey Ponomarev - Stack Overflow
Viewing all articles
Browse latest Browse all 58

Answer by Sergey Ponomarev for Format a float to n decimal places and no trailing zeros

$
0
0

We must trim those zeros ourselves. We can use TrimRight(priceStr, "0."), but I've written a faster trimmer:

func formatPrice(price float32) string {    // truncate to 3 digits after point    priceStr := strconv.FormatFloat(float64(price), 'f', 3, 32)    priceStr = trimFloatTrailingZeros(priceStr)    return priceStr}// trimFloatTrailingZeros the FormatFloat add padding zeros e.g. 20.900 to 20.9 or 10.0 to 10// Note: the number must contain the decimal dot e.g. as result of formatfunc trimFloatTrailingZeros2(s []byte) []byte {    i := len(s) - 1    for ; i >= 1; i-- {        digit := s[i]        if digit == '0' {        } else {            if digit == '.' {                return s[:i]            } else {                return s[:i+1]            }        }    }    return s}

Viewing all articles
Browse latest Browse all 58

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>