w3resource

Python: Round a floating-point number to specified number

Python Basic: Exercise-119 with Solution

Write a Python program to round a floating-point number to specified number decimal places.

Sample Solution:

Round to specified Decimals using %f Function:

Python Code:

order_amt = 212.374
print('\nThe total order amount comes to %f' % order_amt)
print('The total order amount comes to %.2f' % order_amt)
print()

Sample Output:

The total order amount comes to 212.374000
The total order amount comes to 212.37

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Round to specified Decimals using format() Function:

Python Code:

order_amt = 212.374
print("\nThe total order amount comes to {:0.6f}".format(order_amt))
print("\nThe total order amount comes to {:0.2f}".format(order_amt))

Sample Output:

The total order amount comes to 212.374000

The total order amount comes to 212.37

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to create a bytearray from a list.
Next: Write a Python program to format a specified string limiting the length of a string.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Try-catch-else construct:

try:
  foo() 
except Exception: 
  print("Exception occured")
else:
  print("Exception didnt occur")
finally:
  print("Always gets here")