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 short, say we have the following example:
print("{0:.3f}".format(num)) # I cannot do print("{}".format(num))
# because I don't want all the decimals
Is there a "Pythy" way to ensure e.g. in case num == 1
that I print 1
instead of 1.000
(I mean other than cluttering my code with if
statements)
Use the round() function to print a float to 2 decimal places, e.g. print(round(my_float, 2)) . The round() function will round the floating-point number to 2 decimal places and will return the result.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With