Home > Article > Backend Development > How Do I Truncate a Float to a Specific Number of Decimal Places Without Rounding?
How to Remove Digits from a Float
To remove digits from a float and retain a specific number of digits after the decimal point, follow these steps:
Implementation (Python 2.7 and 3.1 ):
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]])
Implementation (Older Versions of Python):
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:
Special Considerations:
The above is the detailed content of How Do I Truncate a Float to a Specific Number of Decimal Places Without Rounding?. For more information, please follow other related articles on the PHP Chinese website!