"0" 1.00" /> "0" 1.00" /> "0" 1.00"/>

c++ boost format float - how to specify that I do not want . and following zeros

3.3k Views Asked by At

I would like to use boost::format to convert a float number to string. These are several examples for the expected results:

0.5     -> "0.5"
0       -> "0"
1.00001 -> "1"
3.66    -> "3.7"

I am using currently

boost::format("%1$.1f")

it works mostly, but the result of 0 is "0.0" and 1.00001 is "1.0" when I want "0" and "1" instead.

What do I need to change to get rid of the pointless .0?

1

There are 1 best solutions below

4
Mark Ransom On

Use a conditional to choose between two formats.

boost::format(abs(x-floor(x+0.05)) < 0.1 ? "%1$.0f" : "%1$.1f")