Removing decimals from a number in Python can be done in several ways depending on whether you want to truncate, round, or manipulate the number. Below are some common methods to achieve this:
1. Truncate Decimal Using int()
The int()
function can convert a float to an integer by removing the decimal part without rounding:
num = 12.345
integer_part = int(num)
print(integer_part) # Output: 12
2. Round Decimal Using round()
The round()
function can round the number to the nearest integer or to a specified number of decimal places. By default, it rounds to the nearest integer:
num = 12.345
rounded_value = round(num)
print(rounded_value) # Output: 12
# Round to 1 decimal place
rounded_value = round(num, 1)
print(rounded_value) # Output: 12.3
3. Floor Decimal Using math.floor()
The math.floor()
function rounds the number down to the nearest integer:
import math
num = 12.345
floor_value = math.floor(num)
print(floor_value) # Output: 12
4. Ceiling Decimal Using math.ceil()
The math.ceil()
function rounds the number up to the nearest integer:
import math
num = 12.345
ceil_value = math.ceil(num)
print(ceil_value) # Output: 13
5. Convert to String and Remove Decimal
Another method is to convert the number to a string, split at the decimal point, and take the integer part:
num = 12.345
num_str = str(num)
integer_part = num_str.split('.')[0]
print(integer_part) # Output: '12'
6. Using floor_divide
for Integer Division
If you want to remove the decimal by performing integer division, use the floor division operator //
:
num = 12.345
integer_part = num // 1
print(integer_part) # Output: 12.0 (float type)
7. Conclusion
Depending on your needs, you can remove decimals using different methods such as truncation, rounding, flooring, or using string operations. Each method has its use case, so choose the one that best fits your requirements.