Reputation: 423
I'm trying to convert decimal to base 36 (...8,9,a,b,c...x,y,z,10,11...) but when I run my code I get a bunch of floats instead of integers.
def trc(n):
if (n < 0): print(0, end='')
elif (n<=1): print(n, end='')
else:
trc( n / 36 )
x =(n%36)
if (x < 10): print(x, end='')
else: print(chr(x+87), end='')
I based this code off of this.
Upvotes: 1
Views: 4551
Reputation: 35
You could just do this:
def trc(n):
return(int(str(n), base = 36))
Then print(trc(x))
to get x
in base 36. This solution works for any base.
However it doesn't give you the letters of base 36: instead of 'z' it returns 36.
You would need to make a seperate program for that.
It should be good enough in most cases, unless you're working with something like excel that needs the letters.
Upvotes: -1
Reputation: 104792
In Python 3, the /
operator does floating point division, even when both arguments are integers. This is a change from Python 2, where dividing two integers would discard the fractional part.
You can explicitly request integer division by using the //
operator. The result will be rounded towards negative infinity. Or, since you're also calculating the modulus, you could use divmod
to get them both at the same time:
else:
n, x = divmod(n, 36)
trc(n)
if x < 10: # ...
Upvotes: 2