How to truncate in Python
Learn how to truncate in Python. Discover different methods, tips, real-world applications, and how to debug common errors.

To truncate a number in Python is a fundamental operation for data work and financial math. The process removes a number's decimal part and does not round the integer value.
In this article, you’ll explore techniques and their real-world applications. You will also find practical tips and advice to fix errors, which helps you select the right approach for your project.
Basic truncation with int()
number = 3.14159
truncated = int(number)
print(f"Original: {number}, Truncated: {truncated}")--OUTPUT--Original: 3.14159, Truncated: 3
The built-in int() function offers the most direct path to truncation. When you pass a floating-point number to int(), it doesn't perform any mathematical rounding. Instead, it simply discards everything after the decimal point, effectively chopping off the fractional part.
This method is efficient for a few key reasons:
- It's a core Python function, so you don't need to import any libraries.
- Its behavior is predictable, always truncating towards zero. For example,
int(-3.9)results in-3, not-4.
Common truncation methods
While int() is a quick solution, other methods offer more explicit control for truncating numbers to a specific decimal place or even shortening strings.
Using math.trunc() for clean truncation
import math
number = -3.14159
truncated = math.trunc(number)
print(f"Original: {number}, Truncated: {truncated}")--OUTPUT--Original: -3.14159, Truncated: -3
For more readable code, you can use the math.trunc() function after importing the math module. While it behaves identically to int(), its name explicitly communicates your intent to truncate a number.
- It always returns the integer part of a number by removing the fractional component.
- Like
int(), it truncates toward zero. For example,math.trunc(-3.14)gives you-3. - The primary benefit is code clarity—you're signaling a mathematical operation, not just a type conversion.
Truncating to specific decimal places
number = 3.14159
decimal_places = 2
truncated = int(number * 10**decimal_places) / 10**decimal_places
print(f"Original: {number}, Truncated to {decimal_places} decimal places: {truncated}")--OUTPUT--Original: 3.14159, Truncated to 2 decimal places: 3.14
When you need to truncate a number to a specific number of decimal places, you can use a simple mathematical trick. This approach shifts the decimal point, removes the unwanted digits, and then shifts it back.
- First, you multiply your number by
10**decimal_placesto move the decimal point to the right. - Next, you apply
int()to remove the fractional part of the shifted number. - Finally, you divide the result by
10**decimal_placesto move the decimal point back, leaving you with the truncated value.
Truncating strings to a specific length
text = "Python is amazing for data processing"
max_length = 10
truncated = text[:max_length]
print(f"Original: '{text}', Truncated: '{truncated}'")--OUTPUT--Original: 'Python is amazing for data processing', Truncated: 'Python is '
Truncation isn't limited to numbers; you can also shorten strings using Python's slicing syntax. This technique is perfect for creating text previews or fitting content into a fixed space. The expression text[:max_length] extracts a portion of the string without modifying the original.
- Slicing creates a new string from the beginning up to, but not including, the specified index.
- It’s an efficient, readable way to get a substring without importing any modules.
Advanced truncation techniques
When standard functions don't quite fit, you can achieve more nuanced truncation using string formatting, sequence slicing, or by building your own custom logic.
Using string formatting for numeric truncation
number = 3.14159265359
truncated_2dp = f"{number:.2f}"
truncated_0dp = f"{number:.0f}"
print(f"Original: {number}, 2 decimal places: {truncated_2dp}, 0 decimal places: {truncated_0dp}")--OUTPUT--Original: 3.14159265359, 2 decimal places: 3.14, 0 decimal places: 3
Python's f-strings provide a quick way to control a number's display, effectively truncating it to a set number of decimal places for presentation. Using a format specifier like :.2f instructs Python to format the number as a string with exactly two digits after the decimal point.
- The syntax
{value:.Nf}formats the number toNdecimal places. - It's important to know this method rounds the number; it doesn't simply chop off digits like
math.trunc(). - The result is a string, not a float, so you'd need to convert it back if you plan on doing more calculations.
Truncating lists and sequences
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
truncated_list = original_list[:5]
print(f"Original: {original_list}, Truncated: {truncated_list}")--OUTPUT--Original: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], Truncated: [1, 2, 3, 4, 5]
The same slicing syntax you saw with strings is just as effective for lists, tuples, and other sequences. Using an expression like original_list[:5] creates a new list containing a subset of the original's elements from the start up to the specified index.
- This operation is non-destructive, meaning it returns a new, shorter list while leaving the
original_listcompletely intact. - It's a versatile and Pythonic way to manage sequence lengths without needing extra functions.
Creating a custom truncation function
def truncate_value(value, max_length, suffix="..."):
return value[:max_length] + suffix if len(value) > max_length else value
text = "Python programming is fun and powerful"
print(truncate_value(text, 10))
print(truncate_value(text, 20, " (more)"))--OUTPUT--Python pr...
Python programming (more)
Creating a custom function like truncate_value gives you more control over how content is shortened. This approach uses a conditional expression to check if the input's length exceeds a max_length before slicing it. If the content is shorter, it remains unchanged.
- It intelligently adds a
suffix, such as..., only when truncation occurs, clearly indicating that text is missing. - You can customize the suffix by passing a different string, like
" (more)", making it flexible for various UI needs.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
The truncation techniques we've explored, from simple int() conversions to custom functions, can be turned into production-ready tools with the agent.
- Build a currency converter that truncates exchange rates to a specific decimal place for clear financial calculations.
- Create a content preview generator that shortens article descriptions or user comments to a fixed length using string slicing.
- Deploy a data dashboard that displays a truncated list of top-performing items from a larger dataset.
Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically, all in your browser.
Common errors and challenges
While truncation seems straightforward, a few common pitfalls can trip you up when dealing with negative numbers and different data types.
Forgetting that int() truncates toward zero
A frequent point of confusion is how int() handles negative numbers, as it always truncates toward zero.
- This means
int(-5.7)becomes-5, not-6, because the function simply chops off the decimal part. - If your goal is to always round down to the nearest integer, you should use
math.floor()instead, which would correctly evaluate-5.7as-6.
Handling string-to-number conversion errors when using int()
You'll encounter a ValueError if you try to convert a string containing a decimal point directly into an integer.
- Code like
int("123.45")fails because the string isn't formatted as a whole number. - The correct approach is a two-step process: first convert the string to a float with
float("123.45"), and then applyint()to that result.
Unexpected results with floating-point truncation using int()
Floating-point arithmetic can sometimes produce unexpected truncation results due to the way computers store decimal numbers internally.
- A number that appears as
8.0might actually be stored as something like7.999999999999999. Applyingint()to this value gives you7. - This isn't a Python bug but a fundamental aspect of binary computing. For applications like finance where precision is critical, use Python's
decimalmodule to prevent these errors.
Forgetting that int() truncates toward zero
It's easy to assume int() rounds numbers down, but with negative values, its behavior can be surprising. The function always truncates toward zero, which means it just removes the decimal part. See how this plays out in the code below.
negative_value = -3.7
truncated = int(negative_value) # Expecting -4 if rounding down
print(f"Original: {negative_value}, Truncated: {truncated}")
The output is -3 because int() discards the decimal part instead of rounding down to the nearest integer, which would be -4. This behavior can be counterintuitive. The code below shows the correct function for this task.
import math
negative_value = -3.7
floor_value = math.floor(negative_value) # Use floor() for rounding down
print(f"Original: {negative_value}, Floor: {floor_value}")
When you need to consistently round down, math.floor() is the right tool for the job. It ensures predictable behavior, especially with negative numbers.
- Unlike
int(), which truncates toward zero,math.floor()always rounds to the nearest integer less than or equal to the value. - This is why it correctly evaluates
-3.7as-4, making it essential for financial math or data analysis where rounding rules must be strict.
Handling string-to-number conversion errors when using int()
A common mistake is trying to convert a string containing a decimal point directly to an integer with int(). This action triggers a ValueError because the function only accepts strings representing whole numbers. The following code demonstrates this exact scenario.
user_input = "3.14"
truncated = int(user_input) # ValueError: invalid literal for int()
print(f"Input: {user_input}, Truncated: {truncated}")
The int() function can't parse the decimal point in "3.14", as it only processes strings representing whole numbers. This mismatch triggers the ValueError. The correct approach requires an intermediate conversion, as shown in the code below.
user_input = "3.14"
truncated = int(float(user_input)) # Convert to float first
print(f"Input: {user_input}, Truncated: {truncated}")
The solution is a two-step process because int() can't parse strings that contain a decimal point. You must first convert the string to a float, then truncate that float to an integer.
- Use
float()to change the string into a floating-point number. - Then, apply
int()to the resulting float to get the truncated integer.
This is a common scenario to watch for when handling user input or data from files, which often arrive as strings.
Unexpected results with floating-point truncation using int()
Floating-point math isn't always exact, which can cause unexpected results when you truncate numbers with int(). A number that looks simple, like 0.3, might be stored with a tiny inaccuracy, leading to calculation errors. The following code demonstrates this problem.
value = 0.1 + 0.2 # Results in 0.30000000000000004
truncated = int(value * 10) / 10 # Might not be 0.3 as expected
print(f"Value: {value}, Truncated to 0.1 precision: {truncated}")
Because the initial value is slightly off, multiplying by 10 magnifies that error. The int() function then truncates the wrong value, making the final result unreliable. The following code shows how to handle this correctly.
import math
value = 0.1 + 0.2
truncated = math.floor(round(value, 10) * 10) / 10 # Round first, then truncate
print(f"Value: {value}, Truncated to 0.1 precision: {truncated}")
The solution is to round the number to a reasonable precision before you truncate it. This step corrects the small floating-point errors that binary math can introduce. By applying round() first, you stabilize the value, ensuring your truncation logic works on the number you actually expect.
- This technique is essential in financial or scientific contexts where even tiny errors can have a big impact.
- It prevents unexpected outcomes from standard truncation methods.
Real-world applications
Now that you can avoid common errors, you can use truncation for practical applications like creating comment previews and analyzing datasets.
Truncating user comments for preview
In many applications, you'll need to shorten long comments into previews to keep the user interface clean, a task easily handled with a custom function and string slicing.
def create_comment_preview(comment, max_length=30):
if len(comment) <= max_length:
return comment
return comment[:max_length].rstrip() + "..."
user_comment = "This Python tutorial is extremely helpful for beginners and advanced programmers alike!"
preview = create_comment_preview(user_comment)
print(f"Full comment: {user_comment}")
print(f"Preview: {preview}")
The key to this function is its use of rstrip() to create a polished preview. When a long comment is sliced with comment[:max_length], the cut might happen right after a space. Without rstrip(), you'd get an awkward gap, like "some text ...". This method cleans up that trailing whitespace before adding the ellipsis. It ensures the ... always attaches neatly to the last word, making the truncated text look much cleaner. The function only applies this logic to comments that actually exceed the max_length.
Truncating outliers in data analysis with numpy
For data analysis, you can use the numpy library to manage outliers by truncating any values that fall above a certain statistical threshold, preventing them from distorting your findings.
import numpy as np
data = [23, 25, 27, 28, 29, 30, 31, 32, 45, 120]
mean = np.mean(data)
std_dev = np.std(data)
threshold = mean + 2 * std_dev
truncated_data = [min(x, threshold) for x in data]
print(f"Original data: {data}")
print(f"Truncating values above: {threshold:.2f}")
print(f"Truncated data: {truncated_data}")
This approach uses the numpy library to cap extreme values in a dataset. It's a common way to handle outliers without removing them, which preserves the dataset's size. The process works in two main steps:
- First, it calculates a statistical
thresholdusingnp.mean()andnp.std(). This value is set at two standard deviations above the data's mean, a standard method for identifying outliers. - Then, a list comprehension iterates through the data, using
min(x, threshold)to replace any number greater than the threshold with the threshold value itself.
Get started with Replit
Turn these truncation techniques into a real tool. Give Replit Agent a prompt like, “Build a loan calculator that truncates interest to the cent,” or “Create a UI that truncates long usernames.”
The agent writes the code, tests for errors, and deploys your app automatically. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



%2520in%2520Python.png)