3 Ways to Round a Number to Two Decimals in Python

Do The Thing
1 min readJan 10, 2023

--

Python offers a variety of ways to round a number to two decimals. Here are three options you can use:

Option 1: Using the round() function

The built-in round() function allows you to round a number to a specified number of decimal places. To round a number to two decimals, you can use the following syntax:

rounded_number = round(original_number, 2)

Here’s an example

>>> original_number = 3.14159
>>> rounded_number = round(original_number, 2)
>>> print(rounded_number)
3.14

Option 2: Using the format() function

You can also use the format() function to round a number to two decimals. Here's the syntax:

rounded_number = format(original_number, '.2f')

Here’s an example:

>>> original_number = 3.14159
>>> rounded_number = format(original_number, '.2f')
>>> print(rounded_number)
3.14

Option 3: Using the decimal module

If you need to perform more complex decimal operations, you can use the decimal module from the Python standard library. Here's an example of how to use it to round a number to two decimals:

from decimal import Decimal
original_number = 3.14159
rounded_number = Decimal(original_number).quantize(Decimal('0.01'))
print(rounded_number)

Output:

3.14

I hope this helps! Let me know if you have any questions or need further clarification.

--

--

Do The Thing
Do The Thing

No responses yet