-1

I have this value :

a = 1.01010101 

And i need to take all the numbers after the point, convert them into an int. Create a new variable and put this int in an new variable. So i need an output like this

b = 01010101

I can't make this:

a -= 1
b = a*(10**8)

because I don't know the number before the point. Is it also possible to do it without writing a new function? Sorry for my english. Have a good day

Fatih Akman
  • 39
  • 1
  • 5
  • Are you sure you want to have an integer? Your example is ambigous since the integer will not have a leading zero. Do you want to have '01010101' (str), 1010101 (int) as result which is a big difference. If you really want to have the integer the answer below is correct. – Falk Schuetzenmeister Dec 20 '18 at 20:30
  • 1
    That doesn't make sense for multiple reasons, including floating-point representation issues *and* integer representation issues. – user2357112 Dec 20 '18 at 20:34
  • Or are you looking for something like 0.01010101? – Falk Schuetzenmeister Dec 20 '18 at 20:35

2 Answers2

1

The math.trunc() function will give you the integer part:

>>> import math
>>> math.trunc(1.01010101)
1

you can then subtract, however you'll likely run into ieee floating point issues that may be surprising:

>>> a = 1.01010101
>>> a -= math.trunc(a)
>>> a
0.010101010000000077
>>> b = a * 10**8
>>> b
1010101.0000000077

in many cases you can just truncate the last number to get the expected integer, but I'd suggest reading https://docs.python.org/2/tutorial/floatingpoint.html to get a deeper understanding.

Python has a decimal module that handles base-10 arithmetic more faithfully:

import decimal.Decimal as D
>>> a = D('1.01010101')
>>> a
Decimal('1.01010101')
>>> math.trunc(a)
1
>>> a -= math.trunc(a)
>>> a
Decimal('0.01010101')
>>> a * 10**8
Decimal('1010101.00000000')
>>> b = int(a * 10**8)
>>> b
1010101

in this version there will be no floating point artifacts in the b = ... line.

thebjorn
  • 26,297
  • 11
  • 96
  • 138
0

You can do this:

a = 1.01010101
b = str(a).split('.')[1]

This should give you "01010101".

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42