Python: 4 Ways to Round a Number

Updated: June 3, 2023 By: Khue Post a comment

Using the round() function

round() is a built-in function of Python that provides a simple and straightforward way to round a number to a given precision in decimal digits.

Example:

number = 1.23456

# Round to 3 decimal places
rounded_number = round(number, 3)
print(rounded_number)

# Round to 2 decimal places
rounded_number = round(number, 2)
print(rounded_number)

Output:

1.235
1.23

Using the math.floor() and math.ceil() functions

Example:

import math

number = 1.55677777789

# Round up to the nearest integer
rounded_up = math.ceil(number)
print(rounded_up)   

# Round down to the nearest integer
rounded_down = math.floor(number)
print(rounded_down)

Output:

2
1

Using the format() function

You can round a floating point number by using the format() function like so:

number = 3.14159

# Format to 4 decimal places
# The result is a string
rounded_number_1 = format(number, ".4f")
# Convert to float
rounded_number_1 = float(rounded_number_1)
print(rounded_number_1)


# Format to 2 decimal places
# The result is a string
rounded_number_2 = format(number, ".2f")
# Convert to float
rounded_number_2 = float(rounded_number_2)
print(rounded_number_2)

Output:

3.1416
3.14

Using the decimal module

The quantize() method returns a value equal to the first operand after rounding and having the exponent of the second operand. You can make use of it for the purpose.

Code example:

from decimal import Decimal

number = 3.45678933333333

decimal_number = Decimal(number)
rounded_number = decimal_number.quantize(Decimal("0.00"))
print(rounded_number) 

Output:

3.46

The type of the output is decimal. You can convert it to a float by using the float() function:

rounded_number_float = float(rounded_number)

That’s it. If you have any questions, feel free to leave a comment.