1

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.

Matteo Brini
  • 185
  • 7

2 Answers2

2

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
yatu
  • 86,083
  • 12
  • 84
  • 139
0

it seems the first part of your code works right so i didn't touch it.

def digit(x):
  if (x-int(x))==0:
    return 1
  else:
    return '0.'+''.join(['0' for i in str(x).split('.')[1][0:-1]]+['1'])
Kolahzary
  • 31
  • 5