简体   繁体   中英

Count the order of the last digit of a number in Python

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

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'])

The OP was having difficulties with floating numbers. Also, answering the question was a bit awkward when they state that

if the number is 230 then the answer is 1

and

for 1.0 it is 0.1

The following programs works for many floating point number inputs:

import math
for g in [230, 1.0,.104, 1.23, 4.12345]:
    f = g
    sigdif = 0
    while 1:
        f = f - (int(math.ceil(f))-1)
        if f > 0.99999999999:
            break
        if f < 0.00000000001:
            break
        f = 10 * f
        sigdif = sigdif -1
    print(g,sigdif)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM