0
0
PythonHow-ToBeginner · 3 min read

How to Truncate Decimal in Python: Simple Methods Explained

To truncate a decimal number in Python, you can use int() or math.trunc() which remove the decimal part without rounding. Another way is to convert the number to a string and slice it to keep only the desired decimal places.
📐

Syntax

Here are common ways to truncate decimals in Python:

  • int(number): Converts the float to an integer by removing the decimal part.
  • math.trunc(number): Truncates the decimal part, similar to int().
  • str(number)[:index]: Slices the string representation to keep specific decimal places.
python
import math

# Using int()
truncated_int = int(3.987)

# Using math.trunc()
truncated_math = math.trunc(3.987)

# Using string slicing to keep 2 decimals
num = 3.987
truncated_str = str(num)[:4]  # '3.9' (not precise for all cases)
💻

Example

This example shows how to truncate a float number to remove decimals using int() and math.trunc(). It also shows a simple way to keep two decimal places by string slicing (note this is not always precise for all numbers).

python
import math

def truncate_decimal(number):
    truncated_int = int(number)
    truncated_math = math.trunc(number)
    # Keep two decimals by string slicing (simple approach)
    str_num = str(number)
    if '.' in str_num:
        point_index = str_num.index('.')
        truncated_two_decimals = str_num[:point_index+3]
    else:
        truncated_two_decimals = str_num
    return truncated_int, truncated_math, truncated_two_decimals

num = 5.6789
result = truncate_decimal(num)
print(result)
Output
(5, 5, '5.67')
⚠️

Common Pitfalls

Many beginners confuse truncation with rounding. int() and math.trunc() simply cut off decimals without rounding up or down. Using string slicing to keep decimals can be unreliable because float to string conversion may vary.

Also, using round() does not truncate but rounds the number, which is different.

python
import math

num = 4.999

# Wrong: round() rounds the number
print(round(num))  # Output: 5

# Right: int() truncates without rounding
print(int(num))    # Output: 4

# Right: math.trunc() truncates without rounding
print(math.trunc(num))  # Output: 4
Output
5 4 4
📊

Quick Reference

MethodDescriptionExample
int()Converts float to int by removing decimalsint(3.9) → 3
math.trunc()Truncates decimal part without roundingmath.trunc(3.9) → 3
String slicingCuts string to keep fixed decimals (simple)'3.1415'[:4] → '3.14'
round()Rounds number, not truncatesround(3.9) → 4

Key Takeaways

Use int() or math.trunc() to remove decimal parts without rounding.
String slicing can keep fixed decimals but may be unreliable for all floats.
round() does not truncate; it rounds the number.
Truncation simply cuts off decimals, it does not change the integer part.
Always test your method with different numbers to ensure expected truncation.