Format the float in n decimal places and without trailing zeros

I want to display a float with the whole integer part and up to two decimal places for the fractional part without trailing zeros.

http://play.golang.org/p/mAdQl6erWX :

// Desired output: // "1.9" // "10.9" // "100.9" fmt.Println("2g:") fmt.Println(fmt.Sprintf("%.2g", 1.900)) // outputs "1.9" fmt.Println(fmt.Sprintf("%.2g", 10.900)) // outputs "11" fmt.Println(fmt.Sprintf("%.2g", 100.900)) // outputs "1e+02" fmt.Println("\n2f:") fmt.Println(fmt.Sprintf("%.2f", 1.900)) // outputs "1.90" fmt.Println(fmt.Sprintf("%.2f", 10.900)) // outputs "10.90" fmt.Println(fmt.Sprintf("%.2f", 100.900)) // outputs "100.90" 

When formatting with 2g , a problem arises when it starts to round, when an integer increases the order of magnitude. In addition, it sometimes displays numbers with e .

When formatting with 2f there is a problem with displaying trailing zeros. I could write a post-processing function that removes trailing zeros, but I would rather do it with Sprintf .

Can this be done in a general way using Sprintf ?
If not, what is the way to do this?

+10
source share
3 answers

strconv.FormatFloat(10.900, 'f', -1, 64)

This will result in 10.9 .

-1 as the third parameter indicates the function to print the smallest digits needed to accurately represent the float.

See here: https://golang.org/pkg/strconv/#FormatFloat

+16
source

Not sure about Sprintf , but for it to work. Just crop to the 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 
+3
source

I used the following function to achieve 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"), ".") } 
0
source

All Articles