In this tutorial we will learn how to remove decimals from a number in Python.
Removing decimals from a number in Python
The int() method in Python can be used to turn a value into an integer and eliminate all decimals. This will effectively truncate the number, removing all decimal places.
Here's an example:
number = 3.14159
integer_number = int(number)
print(integer_number) # Output: 3
In the above example, a floating-point number with the value 3.14159 usede as the initial value. We then use the int()
function to convert number
to an integer, which gives us 3
. We then print the value of integer number to the console after storing the resulting integer in the integer number variable.
Note that this method simply removes the decimal places without rounding the number.Use the round() function before converting to an integer if you need to round the value before removing the decimals. For example:
number = 3.14159
rounded_number = round(number)
integer_number = int(rounded_number)
print(integer_number) # Output: 3
In this case, we round the integer using the round() method to the closest whole number, which gives us the number 3. We then convert the rounded number to an integer using int()
, and print the resulting value to the console.