2

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.

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

Harton
  • 106
  • 2
  • 9
  • 2
    To do rounding you use strings or BigDecimals floats will worek as you see they are well defined but not useful for rounding see http://stackoverflow.com/questions/588004/is-floating-point-math-broken and for your last comment [What Every Computer Scientist Should Know About Floating-Point Arithmetic](What Every Computer Scientist Should Know About Floating-Point Arithmetic) – mmmmmm Nov 05 '16 at 10:27
  • 6
    `3` isn't the last decimal, it's just formatted to look that way. – Peter Wood Nov 05 '16 at 10:28
  • String solutions are valid because string formatting understands maths. If you mean you want to understand precision errors in floating point representations then that's something different. – Peter Wood Nov 05 '16 at 10:30
  • 3
    If you want the nth decimal place, it's probably easiest to multiply the number by `10 ** n` and use `% 10` again. If you want a purely numerical solution, that's not really a programming question. – jonrsharpe Nov 05 '16 at 10:31
  • Not all floats can be represented in machine based form (binary) without losing precision. So, the question, "Give me the last decimal digit of a given number" becomes ill-formed while using built-in types in Python (unless you work with strings). To work with arbitrary precision, you can use 3rd party libraries. – blackpen Nov 05 '16 at 11:01

1 Answers1

4

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 (i.e. the Decimal type). Then a solution might look like this:

>>> import decimal
>>> d = decimal.Decimal('3.14')
>>> d.as_tuple().digits[-1]
4
tyleax
  • 1,556
  • 2
  • 17
  • 45
freidrichen
  • 2,237
  • 1
  • 19
  • 23