Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Last digit of number

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.

like image 380
Kashyap Patel Avatar asked Sep 21 '15 13:09

Kashyap Patel


People also ask

How do you find the last digit of a number?

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.

What is the last digit in mathematics?

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.

What is the last digit of the number 13457 194323?

∴ The Last digit of the number 13457194323 is 3.

What is the last digit of 7 77?

which has last digit 9. The last digit of 7777 is 7 and 72=49, which also has last digit 9.


2 Answers

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.

like image 117
xameeramir Avatar answered Sep 21 '22 03:09

xameeramir


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.

like image 25
Jai Avatar answered Sep 20 '22 03:09

Jai