Format a float to n decimal places and no trailing zeros
strconv.FormatFloat(10.900, 'f', -1, 64)
This will result in 10.9
.
The -1
as the third parameter tells the function to print the fewest digits necessary to accurately represent the float.
See here: https://golang.org/pkg/strconv/#FormatFloat
I used the below func to achive the same:
//return 45.00 with "45" or 45.50 with "45.5"
func betterFormat(num float32) string {
s := fmt.Sprintf("%.4f", num)
return strings.TrimRight(strings.TrimRight(s, "0"), ".")
}
Use the below function to format and control the number of digits.
func FormatFloat(num float64, prc int) string {
var (
zero, dot = "0", "."
str = fmt.Sprintf("%."+strconv.Itoa(prc)+"f", num)
)
return strings.TrimRight(strings.TrimRight(str, zero), dot)
}
Here is an example:
// Converts 18.24100100 to 18.24
fmt.Println(FormatFloat(18.24100100, 2))
Not sure for Sprintf
but to make it worked. Just trim right, first 0
then .
.
fmt.Println(strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", 100.900), "0"), ".")) // 100.9
fmt.Println(strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", 100.0), "0"), ".")) // 100