Reputation: 3456
Consider this:
"{:.14f}".format(0.123)
This will produce the following output:
'0.12300000000000'
But what I would like to have is this:
'0.123'
Is there a standard way to format such a float in a way where trailing zeros are removed automatically? (I'd like to avoid post processing the string as this would be much more expensive than having some formatter do this directly during formatting.)
Sorry, what I've forgot to add to this question a little bit of additional information.
The reason why I need dynamic precision is that I want to avoid the typical exponential notation of floating point numbers. That is the reason why I use something like .14f
here: It forces output to not use any e-notation. But unfortunately this adds completely unnecessary tailing zeros. Normally this would not be unnecessary as this output would provide information about the precision, but in this specific case the text output generated shall be parsed again later: It is used for generating SVG graphics. In order to make numbers more human readable I'd like to output them without trailing zeros.
Upvotes: 0
Views: 127
Reputation: 8564
I guess you can just do this to remove the trailing zeroes:
'{0:.14g}'.format(0.123)
Other examples:
>>> '{0:.14g}'.format(0.1230000)
'0.123'
>>> '{0:.14g}'.format(0.12300000000001)
'0.12300000000001'
>>> '{0:.14g}'.format(0.123456789123459)
'0.12345678912346'
To handle scientific representations, you add another processing for it:
'{:.14g}'.format(float('{0:.14f}'.format(0.123)))
Upvotes: 1