Pratik Panchal
Pratik Panchal

Reputation: 53

How to format a float in python which has variable number of zeros after decimal point?

I have a function that returns a float number which can have from 0 to up to 8 zeros after the decimal point.

I want to format the float in non-scientific notation and display only up to 4 non-zero digits following the zeros after the decimal point.

For example:

1.42 should be formatted as 1.42  
1.4205152 should be formatted as 1.4205  
1.42e-2 should be formatted as 0.0142  
1.452e-4 should be formatted as 0.0001452  
1.49315e-5 should be formatted as 0.00001493  

etc

Is there a format specifier in python to do so, or writing a custom function is the only solution?

Upvotes: 0

Views: 372

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 224032

There is no built-in support for this. That is, there is no format specifier or conversion function that does this directly. You will need to write your own code to do the formatting.

Upvotes: 2

Related Questions