Table of Contents
ToggleWhen we are working with numbers in Python, we sometimes come across situations where we get numbers like 34.00001, 10000.2358, etc. But in certain situations, these decimal points don’t add value to our calculation and we want to round or truncate the decimals.
In this blog, we will see several techniques for truncating decimals using Python. We will go through built-in methods and some third-party libraries. We will also be discussing some of the potential pitfalls when dealing with floating-point numbers and give practical examples to showcase various approaches.
Understanding the Need to Truncate Decimals
Before moving forward, let’s understand why truncation might be necessary. Truncating a decimal means cutting off the fractional part of the number without rounding. In simple terms, we can say that truncation is simply the operation of removing digits after the decimal point without rounding the number up or down.
For example:
- Truncating 5.678 would result in 5.0.
- Truncating 3.14159 would give 3.0.
Built-In Methods for Truncating Decimals in Python
Using int() Function
One of the common and simplest ways to truncate a decimal number in Python is by using the built-in int() function. It converts any floating number to an integer by removing the decimal part.
One of the simplest ways to truncate a decimal number in Python is by using the built-in int() function. This function converts a float to an integer by removing the decimal part, effectively truncating the number.
Example:number = 5.678 truncated = int(number) print(truncated)Output:
5
If we carefully look at the above example, we are converting the floating point number to an integer. We are not rounding a decimal number but simply cutting off everything after the decimal point.
Using math.trunc() to truncate decimals in Python
In Python, we have a math module that provides a more explicit function for truncating a number: math.trunc(). It is a similar function to int(), but makes clear that we are truncating a decimal and not rounding.
Example:
import math number = 3.14159 truncated = math.trunc(number) print(truncated)
This function is useful for readability and clarity.
The math.trunc() function works with both positive and negative numbers, and it always truncates toward zero.
Using // (Floor Division) to truncate floats in Python
Using Floor division can be another approach to truncate a decimal in Python. In Python, floor division is performed using the // operator. It basically divides two numbers and returns the largest integer less than or equal to the result.
Example:number = 7.89 truncated = number // 1 print(truncated)Output:
7.0
The // operator truncates the number by returning an integer by simply discarding the fractional part.
Truncating Decimals In Python with Specified Precision
In certain cases we don’t want to discard all decimals but rather truncate to a specific number of decimal places. Python provides ways to truncate a float to a specific precision which can be useful in financial applications or when we want to control the output format.
Using round() Function For truncating decimal numbers in Python
The round() function is primarily used for rounding but it can be useful for truncating decimals to a certain number of places.
Example:
number = 5.6789 truncated = round(number, 2) print(truncated)
Output
5.68
In the above example the round() function rounds the number to the nearest two decimal places. If you are strictly looking for truncation and not rounding then you can use it in combination with some other methods.
Keep in mind, the round() function rounds numbers, which may not always give you the behavior you expect if you want strict truncation.
Using String Manipulation to truncate float in Python
If you want more control over how the decimal is truncated then this method is for you. You can convert the number to a string and then manipulate the string to remove unwanted decimals.
Example:number = 5.6789 truncated = str(number)[:str(number).find('.') + 3] # Keeps two decimals print(truncated)Output:
5.67
This approach allows us to truncate the number to a specific number of decimal places by manipulating the string representation. It’s useful when we need to format the output.
Dealing with Floating Point Precision Issues
One of the challenges when we are working with floating point numbers is that they are not always represented precisely in memory. This can lead to unexpected results when performing mathematical operations, even including truncation.
AUsing Decimal from decimal Module to solve the issue
To solve floating-point precision issues. In Python, we have a decimal module which gives a more accurate way to handle floating-point arithmetic.
Example:from decimal import Decimal, getcontext #global precision of the decimal context to 6 decimal places getcontext().prec = 6 #creating a decimal number number = Decimal('2.675') truncated = number.quantize(Decimal('1.00')) print(truncated)Output:
2.67
The quantize() method is used to truncate the decimal value to a specific number of decimal places. The value ‘Decimal(‘1.00’)’ inside the quantize method is the template that tells how many decimal points need to be kept.
By using Decimal, you avoid the pitfalls of floating-point representation and can control the precision of your calculations more effectively.
When to Use Truncation
Truncation is useful in various scenarios
- Like in Financial Calculations, where rounding could lead to significant differences in amounts but when we truncate monetary values, it can help us avoid inflation of totals.
- In Data Processing, truncation can help us when we are working with large datasets and need to ensure consistency in numeric data.
- In Scientific Computing precision is critical which can be achieved via Truncation.
Conclusion
Let’s now summarize what we have learned. We have learned various inbuilt methods for truncating decimal numbers like
- Using int() function
- Using math.trunc() function
- Using Decimal module
- Using round() function
Other methods which help us to truncate float numbers.
- Using Floor division
- Using String manipulation
The choice of method depends on the specific needs of your application and how much precision we require. However, we need to be mindful of the pitfalls of floating-point arithmetic and take advantage of Python’s robust libraries to ensure accurate and reliable results.
You can also read about our other blogs on Basic Python MCQs covering functions, exception handling, lists, tuples, dictionaries, and how to split a list in half using Python.
Pingback: Solved EmptyDataError: No columns to parse from file