0

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.

1
  • due to floating point inprecision, there may not be trailing zeros but instead trailing 9s or something Commented Dec 28, 2020 at 8:56

1 Answer 1

1

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))) 
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much for your response. This is good thinking but while reading your answer I understood that I forgot to tell you about a specific requirement: That I want to avoid any exponential "e"-notation. Nevertheless thank you for your answer!
For that, you can do something like this maybe: '{:.14g}'.format(float('{0:.14f}'.format(0.123))) @RegisMay There is no pre- or post- processing, just one argument taken in your function of function.
"{0:.14f}".format(0.123) results in '0.12300000000000'. That's exactly the problem: I'd like to have "0.123" instead ;-)
You need to apply two functions to your input string, including '{:.14g}'.format to the output you get from first format.
Ah! Now i see what you mean! Wow! That's a creative answer ;-) This answer earns to get an upvote just because of the creativity of the approach ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.