0

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'
J Jones
  • 3,060
  • 4
  • 26
  • 43
  • I now agree that the question is duplicate, but I wasn't able to find the duplicate question when I spent ~5 minutes searching Google/stackoverflow looking for the answer. Is that a sufficient reason to leave this question up, or should I delete it? – J Jones Feb 07 '19 at 22:38

1 Answers1

0

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')
J Jones
  • 3,060
  • 4
  • 26
  • 43