Home >Backend Development >Python Tutorial >How to Truncate Float Values to a Specific Number of Decimal Places in Python without Rounding?

How to Truncate Float Values to a Specific Number of Decimal Places in Python without Rounding?

Susan Sarandon
Susan SarandonOriginal
2024-11-06 00:25:02393browse

How to Truncate Float Values to a Specific Number of Decimal Places in Python without Rounding?

How to Truncate Float Values to a Specific Number of Decimal Places

In Python, you can remove digits from a float to achieve a fixed number of digits after the decimal point. Consider the following example:

1.923328437452 → 1.923

Truncating the float to three decimal places results in the desired output of 1.923.

Solution

The function below performs this task:

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]])

Explanation

The function converts the float to a string representation, splitting it into three parts: the integer part, the decimal point, and the fractional part. It then pads the fractional part with zeros up to the specified number of decimal places, ensuring that any excess digits are truncated.

Handling Scientific Notation

The function checks if the float is represented in scientific notation (e or E) and uses a different format function to preserve the exponent.

Older Python Versions

For Python versions earlier than 2.7, you can still truncate floats, but the result may not be as accurate due to limitations in the floating-point formatting mechanism. A possible workaround is to round the float to a higher precision before truncating:

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]])

The above is the detailed content of How to Truncate Float Values to a Specific Number of Decimal Places in Python without Rounding?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn