Truncate to three decimals in Python

Truncate to three decimals in Python

You can use an additional float() around it if you want to preserve it as a float.


You can use the following function to truncate a number to a set number of decimals:

import math
def truncate(number, digits) -> float:
    stepper = 10.0 ** digits
    return math.trunc(stepper * number) / stepper


>>> truncate(1324343032.324325235, 3)

Truncate to three decimals in Python

Ive found another solution (it must be more efficient than string witchcraft workarounds):

>>> import decimal
# By default rounding setting in python is decimal.ROUND_HALF_EVEN
>>> decimal.getcontext().rounding = decimal.ROUND_DOWN
>>> c = decimal.Decimal(34.1499123)
# By default it should return 34.15 due to 99 after 34.14
>>> round(c,2)
>>> float(round(c,2))
>>> print(round(c,2))

About decimals module

About rounding settings

Leave a Reply

Your email address will not be published. Required fields are marked *