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 a specified number of decimal places.

Sample Solution:

Round to specified Decimals using %f Function:

Python Code:

# Define the order amount as a floating-point number.
order_amt = 212.374

# Print the total order amount with 6 decimal places.
print('\nThe total order amount comes to %f' % order_amt)

# Print the total order amount with 2 decimal places using string formatting.
print('The total order amount comes to %.2f' % order_amt)

# Print a blank line for formatting.
print()

Sample Output:

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

Round to specified Decimals using format() Function:

Python Code:

# Define the order amount as a floating-point number.
order_amt = 212.374

# Print the total order amount with 6 decimal places using format.
print("\nThe total order amount comes to {:0.6f}".format(order_amt))

# Print the total order amount with 2 decimal places using format.
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

Python Code Editor:

 

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 Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/python-basic-exercise-119.php