← Go Back
The first argument is the number whose decimals you want to truncate, while the second argument indicates the number of decimals you want to preserve. Note that the function truncates the decimals, but does not round them. To round a floating point number, see How to Round a Number.
To remove all decimals, just cast the number to an integer via
How to Truncate a Floating Point Number
Using this function:def truncate(number: float, max_decimals: int) -> float:
int_part, dec_part = str(number).split(".")
return float(".".join((int_part, dec_part[:max_decimals])))
n = 7.123456
print(truncate(n, 2)) # 7.12
print(truncate(n, 1)) # 7.1
print(truncate(n, 4)) # 7.1234
The first argument is the number whose decimals you want to truncate, while the second argument indicates the number of decimals you want to preserve. Note that the function truncates the decimals, but does not round them. To round a floating point number, see How to Round a Number.
To remove all decimals, just cast the number to an integer via
int()
:n = 7.123456
print(int(n)) # 7
🐍 You might also find interesting: