Skip to main content

How to round a number to a specific decimal place in Python

How to round a number to a specific decimal place in Python.

Here is a step-by-step tutorial on how to round a number to a specific decimal place in Python:

Step 1: Import the decimal module To perform precise decimal rounding, we need to import the decimal module. This module provides a Decimal class that allows us to perform decimal arithmetic.

import decimal

Step 2: Create a Decimal object Next, we need to create a Decimal object to represent our number. We can do this by passing the number as a string to the Decimal constructor.

number = decimal.Decimal('10.98765')

Step 3: Set the desired decimal places Now, we need to determine the number of decimal places to which we want to round our number. We can store this value in a variable for later use.

decimal_places = 2

Step 4: Round the number To round the number to the desired decimal places, we can use the quantize() method of the Decimal object. We pass a Decimal object representing the desired precision as the argument to quantize().

rounded_number = number.quantize(decimal.Decimal('0.' + '0' * decimal_places))

In the above example, we construct a Decimal object representing the desired precision by concatenating a '0.' with a string of '0's of length equal to decimal_places. This ensures that we round to the desired number of decimal places.

Alternatively, we can use the round() function in combination with the Decimal object to achieve the same result.

rounded_number = round(number, decimal_places)

Step 5: Print the rounded number Finally, we can print the rounded number to verify the result.

print(rounded_number)

Putting it all together, here is the complete code:

import decimal

number = decimal.Decimal('10.98765')
decimal_places = 2

rounded_number = number.quantize(decimal.Decimal('0.' + '0' * decimal_places))
# Alternatively: rounded_number = round(number, decimal_places)

print(rounded_number)

This will output 10.99 as the rounded number.

Feel free to adjust the number and decimal_places variables to round other numbers to different decimal places.