Home
Map
round Method, Math RoundCall round to round numbers up and down. With math.ceil a number is rounded up.
Python
This page was last reviewed on Feb 18, 2023.
Round. A number has a fractional part. For example 1.45 is between and 1 and 2 and we want to round it. With round() we can round it to 1 or 1.5.
To always round up, consider the math.ceil method. And to always round down, use math.floor. But to retain a fractional part, round() is helpful.
Round example. This receives one or two arguments. The second argument is optional. Round() returns a rounded number—we use it in an assignment.
Argument 1 This is the number we want to round. For this example, we are rounding the number 1.23456.
Argument 2 This tells how many numbers past the decimal point to keep. The final number is rounded up if the next digit is 5 or more.
number = 1.23456 # Use round built-in. # ... This rounds up or down depending on the last digit. print(round(number)) print(round(number, 0)) print(round(number, 1)) print(round(number, 2)) print(round(number, 3))
1 0 digits 1.0 0 digits 1.2 1 digit 1.23 2 digits 1.235 3 digits, last one rounded up to 5
Round up, down. Let us consider this program. We use math.ceil to always round up to the nearest integer. Round() cannot do this—it will round up or down depending on the fractional value.
Info Ceil will always round up. So the ceil of 1.1 is 2. An integer is returned.
And Floor will round down to the nearest integer. The floor of 1.9 is 1. This is a mathematical function.
import math number = 1.1 # Use math.ceil to round up. result = math.ceil(number) print(result) # The round method will round down because 1.1 is less than 1.5. print(round(number))
2 1
Syntax notes. There is no math.round function in Python 3. Trying to invoke math.round will lead to an AttributeError. Instead, just use round().
Error
Traceback (most recent call last): File "C:\programs\file.py", line 6, in <module> number = math.round(1.1) AttributeError: 'module' object has no attribute 'round'
Math notes. Additional methods in Python can transform numbers as needed. The abs method provides absolute values. Built-in math methods make programs simpler.
math
A review. With round() in Python we gain a way to reduce the number of digits past the decimal place. Round increases or decreases a number based on the last digit.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 18, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.