Remove Digits after Point from Float Number in Python
In this article, we will learn, how we can remove digits after point from a float type number in Python. Those are implemented as follows.
Float to integer using int() Method:
Generally, we remove the digits after floating point of float number by changing the data type from float to integer by using int() Method.
Example – 1:
print(int(3.1))
Output:
3
From above output we can see that 3.1 is converted into integer(3) by using the int() function.
Example- 2:
We can also use this with a variable. Let’s declare a=12.222, and store in variable b then print b.
a=12.222 b=int(a) print(b)
Output:
12
Math module:
There are many built-in modules in python. Out of these modules in Python, math module is an important one.
This module provides some basic mathematical functions.
math module consists of different predefined functions like sin(), cos(), tan(), radians(), log(), exp(), pow(), sqrt(), ceil(), floor(), abs().
Subsequently, for reference of math module visit math module.
Importing Math Module:
import math
Truncate Method:
It is similar to other predefined functions in math module, truncate function remove digits after floating-point.
For positive numbers, it results, floor() operation is done for a given number.
For negative numbers, it results, ceil() operation is done for a given number.
Also, read: Get n Random items from a List in Python
This is because the ceiling function is to round up towards positive infinity.
floor() function is to round down towards negative infinity.
Syntax:
math.trunc(number)
Example for Truncate Function:
import math a=12.222 print(math.trunc(a))
Consequently, the Output is:
12
From the above code, we can see that it consists of 12.222.
Then trunc() function applied on the variable a, so the resultant output is 12.
Example:
import math n=-3.33 print(math.trunc(n))
Output:
-3
From the above code, we can see that n consists of 3.33, and applied truc() function on the n.
Then the result we can see that floor() of n variable(-3).
Leave a Reply