Search code examples
pythonstring-formattingnumber-formatting

How to print significant digits only?


I have not found an answer for this...

Suppose I have the following rational numbers: 0.00000857 and 1.03.

Using %f rounds to 6 digits so 0.00000857 becomes 0.000009. Also 1.03 would be padded to 1.030000. Setting .8f would print 0.00000857 as 0.00000857, but 1.03 would be padded. %g returns exponential notation and I do not want it.

How can I print (stringify) the two numbers as they are, i.e. 0.00000857 and 1.03?


Solution

  • You could just round the float to desired decimal places(6 in your case) and subsequently formate it to such.

    print('{:.6f}'.format(0.00000857))
    

    to remove the undesirable trailing zeros:

    print('{:.6f}'.format(1.03).rstrip('0').rstrip('.'))