Print either an integer or a float with n decimals
With Python 3*, you can just use round()
because in addition to rounding float
s, when applied to an integer it will always return an int
:
>>> num = 1.2345
>>> round(num,3)
1.234
>>> num = 1
>>> round(num,3)
1
This behavior is documented in help(float.__round__)
:
Help on method_descriptor:
__round__(...)
Return the Integral closest to x, rounding half toward even.
When an argument is passed, work like built-in round(x, ndigits).
And help(int.__round__)
:
Help on method_descriptor:
__round__(...)
Rounding an Integral returns itself.
Rounding with an ndigits argument also returns an integer.
* With Python 2, round()
always return
s a float
.
If you need to maintain a fixed-width for float values, you could use the printf-style formatting, like this:
>>> num = 1
>>> print('%0.*f' % (isinstance(num, float) * 3, num))
1
>>> num = 1.2345
>>> print('%0.*f' % (isinstance(num, float) * 3, num))
1.234
>>> num = 1.2
>>> print('%0.*f' % (isinstance(num, float) * 3, num))
1.200