Reputation: 105
So now I have a variable which is x = 1001.0010101
From this x, I wanna separate into two parts:
x = 1001.0010101
val_int = int(x) #get val_int = 1001
val_fract = {0:.5f}".format(a - val_int) #get val_fract = 0.00101
Is it possible to use for loop to iterate the val_fract to be like: (ignore the int part and decimal point)
0
0
1
0
1
I have tried so many times and I couldn't get it done and the system told me
Traceback (most recent call last):
File "python", line 46, in <module>
TypeError: 'float' object is not iterable
Thanks for your help, much appreciated.
Upvotes: 0
Views: 12799
Reputation: 12410
I don't know, why you suggest in your comment that leading zeros are missing:
x = 1001.0010101
#separate fractional from integer part
frac = str(x).split(".")
for digit in frac[1]:
print(digit)
Alternatively, you can transform both parts into lists of integers:
#integer digits
x_int = list(map(int, frac[0]))
#fractional digits
x_frac = list(map(int, frac[1]))
Upvotes: 1
Reputation: 82765
x = 1001.0010101
x = "{0:.5f}".format(x)
for i in str(x).split(".")[1]:
print(i)
Output:
0
0
1
0
1
Upvotes: 1
Reputation: 584
You can use math
module in python to separate decimal and integer part
import math
x = 1001.0010101
math.modf(x)
#output:(0.0010101000000304339, 1001.0)
Iterate as you want
Have doubt about extra numbers in end of decimal read docs
Upvotes: 1