splitting a number into integer and decimal parts

Is there a python way of splitting a number such as 1234.5678 into two parts (1234, 0.5678) i.e. an integer and a decimal part?

+71
python floating-point split
Jul 13 '11 at 15:48
source share
8 answers

Use math.modf :

 import math x = 1234.5678 math.modf(x) # (0.5678000000000338, 1234.0) 
+115
Jul 13 '11 at 15:53
source share

We can use an unknown built-in function; divmod:

 >>> s = 1234.5678 >>> i, d = divmod(s, 1) >>> i 1234.0 >>> d 0.5678000000000338 
+53
Jul 13 '11 at 15:59
source share
 >>> a = 147.234 >>> a % 1 0.23400000000000887 >>> a // 1 147.0 >>> 

If you want the integer part to be integer rather than floating, use int(a//1) . To get a tuple in one pass: (int(a//1), a%1)

EDIT: remember that the decimal part of a floating-point number is approximate , so if you want to represent it as a person, you need to use the decimal library

+33
Jul 13 '11 at 15:50
source share
 intpart,decimalpart = int(value),value-int(value) 

Works for positive numbers.

+13
Jul 13 '11 at 15:51
source share

This option allows you to get the desired accuracy:

 >>> 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) 
+6
02 Sep '16 at 11:35
source share

It also works for me.

 >>> val_int = int(a) >>> val_fract = a - val_int 
+3
Jul 20 '17 at 10:00
source share

So I do it:

 num = 123.456 split_num = str(num).split('.') int_part = int(split_num[0]) decimal_part = int(split_num[1]) 
+1
Mar 23 '16 at 19:20
source share

If you do not mind using NumPy, then:

 In [319]: real = np.array([1234.5678]) In [327]: integ, deci = int(np.floor(real)), np.asscalar(real % 1) In [328]: integ, deci Out[328]: (1234, 0.5678000000000338) 
+1
Dec 03 '17 at 22:38
source share



All Articles