Reputation: 65
For example,
a = 5 * 6.2
print (round(a, 2)
The output is 31.0. I would have expected 31.00.
b = 2.3 * 3.2
print (round(b, 3))
The output is 7.36. I would have expected 7.360.
Upvotes: 1
Views: 154
Reputation: 184290
Python always prints at least one digit after the decimal point so you can tell the difference between integers and floats.
The round()
function merely rounds the number to the specified number of decimal places. It does not control how it is printed. 7.36 and 7.360 are the same number, so the shorter is printed.
To control the printing, you can use formatting. For example:
print(".3f" % b)
Upvotes: 6
Reputation: 1123810
You are confusing rounding with formatting. Rounding produces a new float
object with the rounded value, which is still going to print the same way as any other float:
>>> print(31.00)
31.0
Use the format()
function if you need to produce a string with a specific number of decimals:
>>> print(format(31.0, '.2f'))
31.00
See the Format Specification Mini-Language section for what options you have available.
If the value is part of a larger string, you can use the str.format()
method to embed values into a string template, using the same formatting specifications:
>>> a = 5 * 6.2
>>> print('The value of "a" is {:.2f}'.format(a))
Upvotes: 9
Reputation: 29099
Python does round to 3 decimal places. It is the printing that cuts additional zeros. Try something like print("%.3f" % number)
Upvotes: 5