How do I isolate the last digit in a number?
I.e. I have a variable called number
that is 27 and I want the 7.
(The number never gets above 99.)
If you want a number, use % 10
to isolate the one's place numerically:
var onesOnly = number % 10;
If you want a string, you could convert the number to string and use .substr(-1)
to get just the last digit:
var lastDigit = String(number).substr(-1);
Note: Both methods will be unreliable with very large numbers (for different reasons). That's not an issue you'll have if your number never goes over 99, but if others are using this same technique with large numbers, it seems worth noting:
The numeric approach can fall afoul of the fact that JavaScript's numbers are IEEE-754 double-precision floating-point (a "double"), even when they're whole numbers. The highest reliable whole-number value a double can hold is 9007199254740991, after which we run out of significant bits and it starts getting imprecise even at a whole-number level: 9007199254740993 % 10
is 2, not 3, because a double can't hold the value 9007199254740993 precisely.
The text method falls afoul of scientific notation: Very large numbers are converted to string using scientific notation. For instance, 5823548469823234783234852 converts to "5.823548469823234e+24"
. Consequently, String(5823548469823234783234852).substr(-1)
gives us 4
rather than 2
.
Of course, by the time you hit the scientific notation problem, you're already dealing with numbers that are so imprecise (the first issue) that it's a secondary concern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With