Splitting a number into the integer and decimal parts
Is there a pythonic way of splitting a number such as 1234.5678
into two parts (1234, 0.5678)
i.e. the integer part and the decimal part?
Use math.modf
:
import math
x = 1234.5678
math.modf(x) # (0.5678000000000338, 1234.0)
We can use a not famous built-in function; divmod:
>>> s = 1234.5678
>>> i, d = divmod(s, 1)
>>> i
1234.0
>>> d
0.5678000000000338
>>> a = 147.234
>>> a % 1
0.23400000000000887
>>> a // 1
147.0
>>>
If you want the integer part as an integer and not a float, use int(a//1)
instead. To obtain the tuple in a single passage: (int(a//1), a%1)
EDIT: Remember that the decimal part of a float number is approximate, so if you want to represent it as a human would do, you need to use the decimal library
intpart,decimalpart = int(value),value-int(value)
Works for positive numbers.
This variant allows getting desired precision:
>>> a = 1234.5678
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e0)
(1234, 0.0)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e1)
(1234, 0.5)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e15)
(1234, 0.5678)