How to extract last(end) digit of the Number value using jquery. because i have to check the last digit of number is 0 or 5. so how to get last digit after decimal point
For Ex. var test = 2354.55
Now how to get 5 from this numeric value using jquery. i tried substr but that is only work for string not for Number format
Like if i am use var test = "2354.55";
then it will work but if i use var test = 2354.55
then it will not.
To find last digit of a number, we use modulo operator %. When modulo divided by 10 returns its last digit. To finding first digit of a number is little expensive than last digit. To find first digit of a number we divide the given number by 10 until number is greater than 10.
Finding the last digit of a positive integer is the same as finding the remainder of that number when divided by 10 10 10. In general, the last digit of a power in base n n n is its remainder upon division by n n n. For decimal numbers, we compute m o d 10 \bmod~{10} mod 10.
∴ The Last digit of the number 13457194323 is 3.
which has last digit 9. The last digit of 7777 is 7 and 72=49, which also has last digit 9.
This worked for us:
var sampleNumber = 123456789, lastDigit = sampleNumber % 10; console.log('The last digit of ', sampleNumber, ' is ', lastDigit);
Works for decimals:
var sampleNumber = 12345678.89, lastDigit = Number.isInteger(sampleNumber) ? sampleNumber % 10 : sampleNumber.toString().slice(-1); console.log('The last digit of ', sampleNumber, ' is ', lastDigit);
Click on Run code snippet to verify.
Try this one:
var test = 2354.55; var lastone = +test.toString().split('').pop(); console.log("lastone-->", lastone, "<--typeof", typeof lastone); // with es6 tagged template and es6 spread let getLastDigit = (str, num)=>{ return num.toString(); }; let test2 = 2354.55; let lastone2 = +[...getLastDigit`${test2}`].pop(); console.log("lastone2-->", lastone2, "<--typeof", typeof lastone2);
Updates with ES6/ES2015:
We can use tagged template in such case as numbers are not iterable. So, we need to convert the number to a string representation of it. Then just spread it and get the last number popped.
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