Truncate Float in Python
Truncating floats makes calculations easier in terms of processing. There are two ways to truncate a number in Python – by rounding to the nearest integer or by dropping the digits after the decimal place.
Â
Truncate Python Float Using round()
The Python round()
function will round a floating-point number to the nearest integer.
Â
number = 46.64359236
truncated = round(number)
print(truncated)
47
Â
Truncate to a Decimal Place in Python
If you need to truncate a float to a specific number of decimal places, use the round()
function and supply the decimal places to preserve as the second argument.
Â
number = 46.64359236
truncated = round(number, 2)
print(truncated)
46.64
Â
Truncate Float Using the Python int() Function
The Python int()
function will strip the decimal places from a number and turn it into an int without rounding up or down.
Â
number = 46.64359236
truncated = int(number)
print(truncated)
46