I want to remove digits from a float to keep a fixed number of digits after the decimal point, without rounding them. For example, I want:
1.923328437452 → 1.923
I need the result as a string to pass to another function, not print it. How can I achieve this using Python truncate float?
I’ve worked with Python for quite some time, and the easiest way I’ve found to truncate a float value (without rounding) is through string manipulation. It’s straightforward and works across Python versions.
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]])
"his method ensures that the number is cut off exactly at the decimal place you specify, without any unexpected rounding happening. It even handles scientific notation gracefully by forcing it into standard floating-point representation.
That’s a solid approach, but if you need to be extra careful about floating-point precision issues (which can happen due to how Python stores floats), I’d recommend using the decimal
module. It gives more control over rounding and truncation.
from decimal import Decimal, ROUND_DOWN
def truncate(f, n):
'''Truncates a float to n decimal places without rounding using Decimal'''
return str(Decimal(f).quantize(Decimal('1e-{0}'.format(n)), rounding=ROUND_DOWN))
The advantage of using Decimal
is that it’s designed for high-precision arithmetic, ensuring no unwanted rounding sneaks in. It also works well for financial calculations where precision is crucial.
I see both approaches working well, but let’s say you’re okay with rounding slightly while still keeping the formatting clean—then a mix of round()
and string formatting is a neat alternative.
def truncate(f, n):
'''Truncates a float to n decimal places using round and string formatting'''
return '{:.{}}'.format(round(f, n), n)
While this method does round the number first, it ensures the final output string is formatted exactly to n
decimal places without trailing digits. This can be useful when you care more about presentation than strict truncation.