Python math.trunc() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
math module

Definition

math.trunc(x) drops the fractional part of x, moving toward zero and returning an int.

For floats and integers, math.trunc(x) matches int(x) and calls the object's __trunc__() method. Unlike math.floor(), it strips decimals symmetrically on both positive and negative numbers.

math.trunc() is a function in Python's standard math module: import it with import math and call math.trunc(...), or import the name directly with from math import trunc.

Syntax

Import math and pass any real number or object with __trunc__().

python
import math

whole = math.trunc(x)
CallWhat it does
math.trunc(3.9)Returns 3.
math.trunc(-3.9)Returns -3 (toward zero, unlike floor's -4).
math.trunc(-0.7)Returns 0.
math.trunc(float("nan"))Raises ValueError: cannot convert NaN.

Use math.trunc(x) when your code specifically means "strip fraction toward zero" rather than "parse text", since int("42") also parses strings.

Function signatures
python
math.trunc(x, /)
# returns: int truncated toward zero (calls x.__trunc__())

Parameters

ParameterDescription
xRequired positional number or custom class defining __trunc__().

Return Value

Return ValueDescription
intInteger part of x with any fractional digits discarded.

Python Examples

Example 1 — Convert Floating-Point Sprite Offsets to Whole Pixels

Drop fractional sub-pixel coordinates toward zero on both sides of the origin.

python
import math

offsets = [3.9, 12.1, -3.9, -0.5]
for pos in offsets:
    whole_px = math.trunc(pos)
    print(f"{pos:>5} -> {whole_px:>2}")

How It Works

  1. Positive sub-pixels dropped. 3.9 drops 0.9 straight down to 3.
  2. Symmetric negative strip. -3.9 drops -0.9 toward zero to -3.
  3. Fractions below one vanish. Any value in (-1, 1) truncates cleanly to 0.

Example 2 — Support math.trunc() in Your Own Numeric Class

Implement __trunc__() on a custom fixed-point class so math.trunc() works directly.

python
import math


class CentsAmount:
    def __init__(self, cents):
        self.cents = cents

    def __trunc__(self):
        whole = abs(self.cents) // 100
        return -whole if self.cents < 0 else whole


for amount in [CentsAmount(499), CentsAmount(-499)]:
    print(math.trunc(amount))

How It Works

  1. Protocol hook. Defining __trunc__(self) tells Python how to strip fractional pennies from custom objects.
  2. Sign-aware truncation. Dividing positive magnitude keeps both 499 and -499 symmetric at 4 and -4.
  3. Returns plain int. Calling math.trunc(amount) delegates straight to __trunc__.

Example 3 — Compare trunc(), floor(), ceil(), and Built-in round()

Contrast all four rounding modes on positive and negative halves and catch NaN errors.

python
import math

for val in [-2.7, -2.5, 2.5, 2.7]:
    print(
        f"{val:>4}: trunc={math.trunc(val):>2} "
        f"floor={math.floor(val):>2} ceil={math.ceil(val):>2} "
        f"round={round(val):>2}"
    )

try:
    math.trunc(float("nan"))
except ValueError:
    print("trunc(nan) raises ValueError")

How It Works

  1. Four distinct behaviors. Only trunc() strips decimals uniformly toward zero across signs.
  2. Half-even round(). Built-in round() sends both -2.5 and 2.5 to their even neighbors -2 and 2.
  3. NaN failure caught. Passing nan raises ValueError.

Frequently Asked Questions

For numbers they do the exact same thing (truncate toward zero). However, int() also parses strings like "42", while math.trunc("42") raises TypeError.
They agree on positive numbers, but on negative fractions math.trunc(-3.9) is -3 (toward zero) while math.floor(-3.9) is -4 (toward -inf).
No, it returns an int. Use math.modf(x) if you want both the fractional and whole parts as floats.
It raises OverflowError.
Yes. Implement a __trunc__(self) method returning an integer.

Next: math.ulp()

Return the value of the least significant bit of float x (Python 3.9+).

ulp() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful