There are various situations when you’re writing Python where you may want to limit the number of digits in a number.
For example, you could be working with data that involves precise measurements or calculations, and you want to be succinct and accurate. This is where limiting the number of digits becomes essential.
Here’s a simple way to limit the number of digits, specifically decimal places, in Python.
Step 1: Using the Round Function
The simplest way to limit the number of decimal places is to use the built-in Python round() function. The round function takes two arguments: the number you want to round and the number of decimal places to which you want to round.
1 2 |
num = 13.14159 rounded_num = round(num, 2) |
This will round the number 13.14159 to 2 decimal places.
Step 2: Using String Formatting
An alternative method is to use string formatting. This method is a bit more complex but provides greater control. The ‘{:0.2f}’.format() method can be used.
1 2 |
num = 13.14159 formatted_num = '{:0.2f}'.format(num) |
The formatted_num will contain the string “13.14”.
Now, both of these methods have their pros and cons. Using the round() function keeps your number as a floating-point number, which can be handy if you need to do more arithmetic with it.
On the other hand, the string formatting method turns your number into a string, which can be useful for printing or displaying the number, but not so great if you need to do further calculations.
Step 3: Using Decimal Module
Python’s decimal module provides support for fast correctly rounded decimal floating point arithmetic. We use the quantize() function from the decimal module which rounds a number to a fixed exponent. This function requires a string as the second parameter, representing the number of digits to maintain.
1 2 3 4 |
from decimal import Decimal num = Decimal(13.14159) rounded_num = num.quantize(Decimal('0.00')) |
The ’rounded_num’ will be Decimal(‘13.14’)
Complete Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#Using round function num = 13.14159 rounded_num = round(num, 2) print(rounded_num) #Using string formatting num = 13.14159 formatted_num = '{:0.2f}'.format(num) print(formatted_num) #Using Decimal Module from decimal import Decimal num = Decimal(13.14159) rounded_num = num.quantize(Decimal('0.00')) print(rounded_num) |
Conclusion
These are some of the ways to limit decimal places in Python using built-in functions and modules.
Depending on the requirements and circumstances, you may choose an appropriate method. It’s a crucial skill in Python programming, particularly when dealing with precise calculations, data analysis, or financial applications.