[image] lichtwicht: (can I answer “not really” ?) Of course! [image] lichtwicht: (what’s a PR?) Ah, sorry. PR = “Pull Request”, which is the mechanism by which changes are proposed for CPython (and other GitHub-hosted projects). See Pull requests documentation - GitHub Docs for much m… Answer from mdickinson on discuss.python.org
🌐
TradingCode
tradingcode.net › python › math › truncate-integers
How to truncate Python values to a whole, integer number?
This function accepts one argument: the value to truncate. It then returns that value as a whole number. The other option is the int() function. When we give this function one argument, it truncates that argument into a whole number.
🌐
datagy
datagy.io › home › python posts › python strings › python: truncate a float (6 different ways)
Python: Truncate a Float (6 Different Ways) • datagy
April 14, 2024 - Being able to output values in ... easier to look at. ... The built-in int() function takes a float and converts it to an integer, thereby truncating a float value by removing its decimal places....
Discussions

Built-in Types ... INT: round or truncate ? please elaborate
Hello, I’m questioning about: ... zero like the related function, math.trunc(). […] now it says (note 3.): Conversion from floating point to integer may round or truncate as in C […] and nothing else…... More on discuss.python.org
🌐 discuss.python.org
4
0
March 14, 2023
python - How to truncate float values? - Stack Overflow
I want to remove digits from a float to have a fixed number of digits after the dot, like: 1.923328437452 → 1.923 I need to output as a string to another function, not print. Also I want to ignore... More on stackoverflow.com
🌐 stackoverflow.com
Format truncated Python float as int in string - Stack Overflow
In my case where I had a database ... to render in an html template the int portion of the float as a workaround. Of course if you don't know in advance the fractional part you would need to carry out a truncation operation of some sort first on the float.... More on stackoverflow.com
🌐 stackoverflow.com
How to truncate a float?
Why do you want to do this? Particularly, why do you want to round to one decimal place when computer numbers are in powers of 2? Your answer is sort of horrifying because of how expensive it is to compute, and the numerical instability, and the problem you mentioned. int(num * 10) / 10 will do what you believe you want to do. More on reddit.com
🌐 r/learnpython
5
2
July 1, 2022
🌐
Delft Stack
delftstack.com › home › howto › python › python truncate float python
How to Truncate Float in Python | Delft Stack
February 2, 2024 - The below example code demonstrates how to use the round() function to truncate a float. # Truncating to the nearest integer number = 5.67 truncated_number = round(number) print(truncated_number)
🌐
CodeSpeedy
codespeedy.com › home › how to truncate a float in python
How to Truncate a Float in Python - CodeSpeedy
February 22, 2022 - We can also use the int() function to truncate a float in python. The syntax is mostly the same as discussed for the math library. The int() function truncate a float in python as it takes float value and converts it into an integer.
🌐
Python.org
discuss.python.org › python help
Built-in Types ... INT: round or truncate ? please elaborate - Python Help - Discussions on Python.org
March 14, 2023 - Hello, I’m questioning about: Built-in Types - Numeric Types - int[…] - note(3) edit:link irrc in PY2 it said: Conversion from floats using int() truncates toward zero like the related function, math.trunc(). […] now it says (note 3.): Conversion from floating point to integer may round or truncate as in C […] and nothing else…
🌐
Skillsugar
skillsugar.com › truncate-float-in-python
Truncate Float in Python - SkillSugar
June 29, 2021 - If you need to truncate a float to a specific number of decimal places, use the round() function and supply the decimal places to preserve as the second argument. number = 46.64359236 truncated = round(number, 2) print(truncated) ... The Python int() function will strip the decimal places from ...
Top answer
1 of 4
165

First, the function, for those who just want some copy-and-paste code:

def truncate(f, n):
    '''Truncates/pads a float f to n decimal places without rounding'''
    s = '{}'.format(f)
    if 'e' in s or 'E' in s:
        return '{0:.{1}f}'.format(f, n)
    i, p, d = s.partition('.')
    return '.'.join([i, (d+'0'*n)[:n]])

This is valid in Python 2.7 and 3.1+. For older versions, it's not possible to get the same "intelligent rounding" effect (at least, not without a lot of complicated code), but rounding to 12 decimal places before truncation will work much of the time:

def truncate(f, n):
    '''Truncates/pads a float f to n decimal places without rounding'''
    s = '%.12f' % f
    i, p, d = s.partition('.')
    return '.'.join([i, (d+'0'*n)[:n]])

Explanation

The core of the underlying method is to convert the value to a string at full precision and then just chop off everything beyond the desired number of characters. The latter step is easy; it can be done either with string manipulation

i, p, d = s.partition('.')
'.'.join([i, (d+'0'*n)[:n]])

or the decimal module

str(Decimal(s).quantize(Decimal((0, (1,), -n)), rounding=ROUND_DOWN))

The first step, converting to a string, is quite difficult because there are some pairs of floating point literals (i.e. what you write in the source code) which both produce the same binary representation and yet should be truncated differently. For example, consider 0.3 and 0.29999999999999998. If you write 0.3 in a Python program, the compiler encodes it using the IEEE floating-point format into the sequence of bits (assuming a 64-bit float)

0011111111010011001100110011001100110011001100110011001100110011

This is the closest value to 0.3 that can accurately be represented as an IEEE float. But if you write 0.29999999999999998 in a Python program, the compiler translates it into exactly the same value. In one case, you meant it to be truncated (to one digit) as 0.3, whereas in the other case you meant it to be truncated as 0.2, but Python can only give one answer. This is a fundamental limitation of Python, or indeed any programming language without lazy evaluation. The truncation function only has access to the binary value stored in the computer's memory, not the string you actually typed into the source code.1

If you decode the sequence of bits back into a decimal number, again using the IEEE 64-bit floating-point format, you get

0.2999999999999999888977697537484345957637...

so a naive implementation would come up with 0.2 even though that's probably not what you want. For more on floating-point representation error, see the Python tutorial.

It's very rare to be working with a floating-point value that is so close to a round number and yet is intentionally not equal to that round number. So when truncating, it probably makes sense to choose the "nicest" decimal representation out of all that could correspond to the value in memory. Python 2.7 and up (but not 3.0) includes a sophisticated algorithm to do just that, which we can access through the default string formatting operation.

'{}'.format(f)

The only caveat is that this acts like a g format specification, in the sense that it uses exponential notation (1.23e+4) if the number is large or small enough. So the method has to catch this case and handle it differently. There are a few cases where using an f format specification instead causes a problem, such as trying to truncate 3e-10 to 28 digits of precision (it produces 0.0000000002999999999999999980), and I'm not yet sure how best to handle those.

If you actually are working with floats that are very close to round numbers but intentionally not equal to them (like 0.29999999999999998 or 99.959999999999994), this will produce some false positives, i.e. it'll round numbers that you didn't want rounded. In that case the solution is to specify a fixed precision.

'{0:.{1}f}'.format(f, sys.float_info.dig + n + 2)

The number of digits of precision to use here doesn't really matter, it only needs to be large enough to ensure that any rounding performed in the string conversion doesn't "bump up" the value to its nice decimal representation. I think sys.float_info.dig + n + 2 may be enough in all cases, but if not that 2 might have to be increased, and it doesn't hurt to do so.

In earlier versions of Python (up to 2.6, or 3.0), the floating point number formatting was a lot more crude, and would regularly produce things like

>>> 1.1
1.1000000000000001

If this is your situation, if you do want to use "nice" decimal representations for truncation, all you can do (as far as I know) is pick some number of digits, less than the full precision representable by a float, and round the number to that many digits before truncating it. A typical choice is 12,

'%.12f' % f

but you can adjust this to suit the numbers you're using.


1Well... I lied. Technically, you can instruct Python to re-parse its own source code and extract the part corresponding to the first argument you pass to the truncation function. If that argument is a floating-point literal, you can just cut it off a certain number of places after the decimal point and return that. However this strategy doesn't work if the argument is a variable, which makes it fairly useless. The following is presented for entertainment value only:

def trunc_introspect(f, n):
    '''Truncates/pads the float f to n decimal places by looking at the caller's source code'''
    current_frame = None
    caller_frame = None
    s = inspect.stack()
    try:
        current_frame = s[0]
        caller_frame = s[1]
        gen = tokenize.tokenize(io.BytesIO(caller_frame[4][caller_frame[5]].encode('utf-8')).readline)
        for token_type, token_string, _, _, _ in gen:
            if token_type == tokenize.NAME and token_string == current_frame[3]:
                next(gen) # left parenthesis
                token_type, token_string, _, _, _ = next(gen) # float literal
                if token_type == tokenize.NUMBER:
                    try:
                        cut_point = token_string.index('.') + n + 1
                    except ValueError: # no decimal in string
                        return token_string + '.' + '0' * n
                    else:
                        if len(token_string) < cut_point:
                            token_string += '0' * (cut_point - len(token_string))
                        return token_string[:cut_point]
                else:
                    raise ValueError('Unable to find floating-point literal (this probably means you called {} with a variable)'.format(current_frame[3]))
                break
    finally:
        del s, current_frame, caller_frame

Generalizing this to handle the case where you pass in a variable seems like a lost cause, since you'd have to trace backwards through the program's execution until you find the floating-point literal which gave the variable its value. If there even is one. Most variables will be initialized from user input or mathematical expressions, in which case the binary representation is all there is.

2 of 4
160
round(1.923328437452, 3)

See Python's documentation on the standard types. You'll need to scroll down a bit to get to the round function. Essentially the second number says how many decimal places to round it to.

Find elsewhere
🌐
Java2Blog
java2blog.com › home › python › truncate float in python
Truncate float in Python - Java2Blog
November 1, 2021 - The following code uses the int() function to truncate float in Python. ... A user-defined function is created, where the given float is first converted to an integer and is multiplied with 10**x as explained above.
🌐
pythoncodelab
pythoncodelab.com › home › how to truncate decimals in python
How to truncate decimals in Python - pythoncodelab
February 8, 2025 - 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.
🌐
Ianwaldron
ianwaldron.com › blog › float-to-integer-conversion-in-python
Float to Integer Conversion In Python | ianwaldron.com
August 25, 2025 - The simplest form of converting a float to an integer is truncation and is implemented with the Python function from the math library trunc(). Truncating means to shorten. When we truncate a number, we're simply dropping the decimal.
🌐
Python Tutorial
pythontutorial.net › home › advanced python › python float to int
How To Convert a Float to an Int in Python
February 20, 2021 - Python provides you with some functions in the math module for converting from a float to an int, including: Truncation · Floor · ceiling · The trunc(x) function returns the integer part of the number x.
🌐
Reddit
reddit.com › r/learnpython › how to truncate a float?
r/learnpython on Reddit: How to truncate a float?
July 1, 2022 -

I have a case where I need to truncate a float to the first decimal place. Very important - truncate, not round.

I wrote this function

def trunc(num : float, precision :int = 1):
    return float(str(num)[0:precision+2])

which works most of the time, but if the number is particularly small, str(num) will return the scientific notation. So str(0.000094) returns 9.4e-05 which in turn means that str(0.000094)[0:3] returns 9.4.

For now I can np.trunc(num*10)/10 but I'm wondering if there's a better way.

🌐
Stack Abuse
stackabuse.com › bytes › limiting-float-decimal-points-in-python
Limiting Float Decimal Points in Python
August 31, 2023 - To achieve the truncation, we multiply the float by 100, convert it to an integer to remove the excess decimal points, and then divide it by 100 to get the truncated value. In this Byte, we explored different ways to limit a float's decimal points in Python using the round(), format(), and ...
🌐
CodeRivers
coderivers.org › blog › python-truncate-float
Python Truncate Float: A Comprehensive Guide - CodeRivers
February 22, 2026 - The math.trunc() function from the math module also truncates a float to an integer. It works in a similar way to the int() function for positive numbers.
🌐
Medium
medium.com › @ryan_forrester_ › converting-floats-to-integers-in-python-a-complete-guide-9ec8c994327d
Converting Floats to Integers in Python: A Complete Guide | by ryan | Medium
November 4, 2024 - def safe_float_to_int(value, method='round'): """ Safely convert a float to int, handling various edge cases. Args: value: The value to convert method: 'round', 'floor', 'ceil', or 'truncate' Returns: Integer value or None if conversion fails """ try: # Handle strings that represent numbers if isinstance(value, str): value = float(value.strip()) # Handle other numeric types value = float(value) # Check for invalid values if math.isnan(value) or math.isinf(value): return None # Convert based on specified method if method == 'round': return round(value) elif method == 'floor': return math.floor(
🌐
W3Schools
w3schools.com › python › ref_math_trunc.asp
Python math.trunc() Method
# Import math Library import math ... print(math.trunc(-99.29)) Try it Yourself » · The math.trunc() method returns the truncated integer part of a number....
🌐
TradingCode
tradingcode.net › python › math › truncate-decimals
Truncate numbers to decimal places in Python • TradingCode
With Python’s math.trunc() function we truncate floating-point values into whole numbers (Python Docs, n.d.). That turns 4.578 into 4 and makes -2.9 into -2. But that function always truncates to an integer, without an option to keep a certain ...
🌐
PyTutorial
pytutorial.com › python-convert-float-to-int-easy-methods-guide
PyTutorial | Python Convert Float to Int | Easy Methods Guide
February 8, 2026 - The built-in int() function is the most direct way. It converts a float to an integer by truncation. Truncation means it removes the decimal part.