In Python, you can get the integer part of a decimal number in the following ways:
Using int()
You can use the int()
method to truncate floating point numbers towards zero, discarding the fractional component of a number and returning only the integer part.
For example:
print(int(10 / 3)) # 3 print(int(-10 / 3)) # -3 print(int(10 / -3)) # -3 print(int(3.333)) # 3 print(int(-3.333)) # -3
print(int(5 / 2)) # 2 print(int(-5 / 2)) # -2 print(int(5 / -2)) # -2 print(int(2.5)) # 2 print(int(-2.5)) # -2
print(int(10 / 1)) # 10 print(int(-10 / 1)) # -10 print(int(10 / -1)) # -10 print(int(10.0)) # 10 print(int(-10.5)) # -10
Using math.floor()
and math.ceil()
To achieve the same effect as with int()
, you can:
- Use
math.floor()
to round down positive integers, and; - Use
math.ceil()
to round up negative integers.
Doing so would truncate a floating point number towards zero. You can implement it, for example, like so:
import math def trunc(num): return math.floor(num) if (num > 0) else math.ceil(num)
You can also implement this using only the math.floor()
method like so:
import math def trunc(num): unsigned_num = math.floor(abs(num)) return -unsigned_num if (num < 0) else unsigned_num
Similarly, you can implement this using only the math.ceil()
method like so:
import math def trunc(num): unsigned_num = math.ceil(-abs(num)) return unsigned_num if (num < 0) else -unsigned_num
Using any of these would yield the same result (as you can see in the examples below):
print(trunc(10 / 3)) # 3 print(trunc(-10 / 3)) # -3 print(trunc(10 / -3)) # -3 print(trunc(3.333)) # 3 print(trunc(-3.333)) # -3
print(trunc(5 / 2)) # 2 print(trunc(-5 / 2)) # -2 print(trunc(5 / -2)) # -2 print(trunc(2.5)) # 2 print(trunc(-2.5)) # -2
print(trunc(10 / 1)) # 10 print(trunc(-10 / 1)) # -10 print(trunc(10 / -1)) # -10 print(trunc(10.0)) # 10 print(trunc(-10.5)) # -10
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.