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
.
%.3f%(1324343032.324325235)
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
Usage:
>>> truncate(1324343032.324325235, 3)
1324343032.324
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)
Decimal(34.14)
>>> float(round(c,2))
34.14
>>> print(round(c,2))
34.14