GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • w3resource
  • Front End
  • HTML
  • CSS
  • JavaScript
  • HTML5
  • Schema.org
  • php.js
  • Twitter Bootstrap
  • Responsive Web Design tutorial
  • Zurb Foundation 3 tutorials
  • Pure CSS
  • HTML5 Canvas
  • JavaScript Course

This view

  • Original page
  • New address

GeezerVison is showing www.w3resource.com — Python: Round a floating-point number to specified number - w3resource

Python: Round a floating-point number to specified number

Last update on May 17 2025 05:44:17 (UTC/GMT +8 hours)


Round Float to Decimals

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

For more Practice: Solve these Related Problems:

  • Write a Python program to round a floating-point number to the nearest integer.
  • Write a Python program to format a float with a specified number of decimal places.
  • Write a Python program to truncate a floating-point number without rounding.
  • Write a Python program to round a list of floating-point numbers to two decimal places.

Go to:

  • Python Basic Exercises Home ↩
  • Python Exercises Home ↩

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.

Python Code Editor:

 

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.


  • Daily Coding Challenges & Projects
  • Weekly Trends and Language Statistics



You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.