Inspired from yesterday exercise , I search for is there any other way to convert a object from float to integer?
The following is my findings:
and small conclusion at the end
There are four syntax available:
- int()
- math.trunc()
- math.floor()
- math.celi()
Method 1. int()
Syntax:
int(x)
Parameter:
x can be a string or number
but only one.
example 1
The string can only be an integer number
str1 = "5"
int(str1)
example 2
If the parameter is not a string, it can have decimal point
str2 = 5.12
int(str2)
The following code will cause error:
str1 = "5,6" # more than one number in a string
str2 = "4.8" # the number in string must in integer
int(str1)
int(str2)
What object will int()be return?
an int object will be returned
which cut off all the number after decimal place
example 1.
str1 = "5"
int(str1)
will have an output
5
example 2
str2 = 5.12
int(str2)
will have an output
5
Method 2. math.trunc()
- need to import math module before use ### Syntax
import math
math.trunc(x)
Parameter
- math.trunc()only takes number as parameter e.g.
math.trunc(5.123)
What object will math.trunc() return?
- an integer will returned
- which will cut off all the fractional part after decimal place
- same as int()
example
import math
num2 = 5
int2 = math.trunc(num2)
print(int2)
will have an output
5
Method 3. math.floor()
- need to import math module before use ### Syntax
import math
math.floor(x)
Parameter
math.floor() can only take number as parameter
What object will math.floor() return?
an integer will returned.
The number will be round down
- that is the largest integer less than or equal to x
example
import math
num2 = 5.9
int2 = math.floor(num2)
print(int2)
num3 = 5.1
int3 = math.floor(num3)
print(int3)
both num2 and num3 will have an output
5
Method 4. math.ceil()
- need to import math before use
import math
math.celi(x)
Parameter
math.celi() can only take number as parameter
What object will math.floor() return?
an integer will returned.
The number will be round up.
- that is the smallest integer greater than or equal to x
example
import math
num2 = 5.9
int2 = math.floor(num2)
print(int2)
num3 = 5.1
int3 = math.floor(num3)
print(int3)
both num2 and num3 will have an output
6
Conclusion
- int() is the most flexible way to convert float object to integer, but will suffer from data lose, same as meth.trunc().
- math.floor() and math.celi() can minimize data lose in the conversion if use properly.
Top comments (0)