In this tutorial, we will learn how to remove decimals in Python. Python is a highly flexible language and offers several ways to perform this operation. We’ll look at using the floor division operator, the int() function, and the math.floor() method, and the round() function.
Method One: Using the floor division operator
The floor division operator (//) when used, returns the largest possible integer. It discards the decimal part and returns the integer part of the division.
1 2 |
result = 50.5123 // 1 print(result) |
When you run the above code, Python will perform the floor division and discard the decimal part of the result.
Method Two: Using the int() function
The int() function can be used to convert a float to an integer. In doing so, it eliminates the decimal part and returns only the integer part of the number.
1 2 3 |
result = int(50.5123) print(result) |
Method Three: Using math.floor()
The math.floor() function works similarly to the floor division operator. It returns the largest integer less than or equal to a given number. You’ll need to import the math module before using this function.
1 2 3 4 5 |
import math result = math.floor(50.5123) print(result) |
Method Four: Using the round()
The round() function can be used to round a number to a certain number of places. If no number of places is specified, it rounds to the nearest whole number.
1 2 3 |
result = round(50.5123) print(result) |
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#Method 1 result1 = 50.5123 // 1 print(result1) #Method 2 result2 = int(50.5123) print(result2) #Method 3 import math result3 = math.floor(50.5123) print(result3) #Method 4 result4 = round(50.5123) print(result4) |
Conclusion
This tutorial described four methods of removing decimal parts of a number in Python. You can choose one depending on your specific needs and requirements. Remember that each method may have different implications depending on the context, especially when it comes to rounding off numbers.
Always assure you have selected the correct method for your mathematical operations to avoid errors or inaccuracies.