简体   繁体   中英

Finding the last digit of decimal number

We all know that if we want to find the last number of 1182973981273983 which is 3 we simply do this:

>>> print(1182973981273983 % 10)
3

But if I want to get the last number of 2387123.23 I was thinking of doing this:

>>> 2387123.23 % 10 ** (-1 * 2)
0.009999999931681564

But it doesn't work. What is the mathematical way of getting the last number a decimal number.

ps String solutions are invalid. We are programmers we need to know how math works.

As people have already pointed out in the comments, this is not possible for floating point numbers; the concept of 'last decimal' simply doesn't apply. See links in comments for more details.

On the other hand, this would work if you were using fixed point arithmetic (ie the Decimal type). Then a solution might look like this:

>>> import decimal
>>> d = decimal.Decimal('3.14')
>>> d.as_tuple().digits[-1]
4

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