Hy everybody, I'm trying to write a program with Python that tells me the order of the last digit of a number: for example if the number is 230 then the answer is 1, for 0.104 it is 0.001, for 1.0 it is 0.1 and so on... I've tried to write something but it does strange things for float numbers: it is approximately right for numbers that do not end with 0, and it is wrong for those ending with 0. This is what I wrote:
def digit(x):
if (x-int(x))==0:
return 1
else:
return 0.1*digit(x*10)
Thanks to anybody who will answer.
You could use decimal.Decimal
to obtain the amount of decimal places, and compute the order of the last digit as 1e^x
, x
can be obtained through the exponent
attribute of the named tuple returned by decimal.Decimal.as_tuple()
:
import decimal
def order_last_digit(d):
dec = decimal.Decimal(str(d))
return 10**dec.as_tuple().exponent
order_last_digit(230) #10^0=1
# 1
order_last_digit(0.104) #10^-3
# 0.001
order_last_digit(1.0)
# 0.1