Search code examples
pythonstring-formatting

Use Python 3 str.format to truncate a float to have no more than x number of digits


I am looking for an expression that will truncate a float to at most a certain number of digits. I want to preserve a certain number of decimals, without having unnecessary trailing 0s.

So, this almost works as desired:

"{0:3.f"}.format(number)

For input 3.123000001:

"{0:.3f}".format(3.1230000001)
'3.123'

Great. But for input 3:

"{0:.3f}".format(3)
'3.000'

Solution

  • I figured out the answer while I was writing the question. Just add .rstrip('0') to the expression. So:

    "{0:3.f}".format(number).rstrip('0')