Print Either An Integer Or A Float With N Decimals
In Python, how can one print a number that might be an integer or real type, when the latter case would require me to limit my printout to a certain amount of digits? Long story sh
Solution 1:
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
.
Solution 2:
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
Solution 3:
If you use a fix number of floating point, you could just use a replace to remove the extra 0
. For instance this would do the trick:
print("{:.3f}".format(1).replace(".000", ""))
Solution 4:
For fix number of decimal point:
>>> num = 0.2
>>> print('%.04*f' % num)
0.2000
>>> num = 3.102
>>> print('%.02*f' % num)
3.10
Post a Comment for "Print Either An Integer Or A Float With N Decimals"