How to get Last digit of number

2020-06-08 08:34发布

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.

7条回答
Evening l夕情丶
2楼-- · 2020-06-08 08:47

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.

查看更多
爷、活的狠高调
3楼-- · 2020-06-08 08:50

Here is another one using .slice():

var test = 2354.55;
var lastDigit = test.toString().slice(-1);
//OR
//var lastDigit = (test + '').slice(-1);

alert(lastDigit);

查看更多
时光不老,我们不散
4楼-- · 2020-06-08 08:52

toString() converts number to string, and charAt() gives you the character at a particular position.

var str = 3232.43;
lastnum = str.toString().charAt( str.length - 1 );
alert( lastnum );

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-06-08 08:54

If you want the digit in the hundredths place, then you can do the following:

test * 100 % 10

The problem with convert to string and getting the last digit is that it does not give the hundredths place value for whole numbers.

查看更多
家丑人穷心不美
6楼-- · 2020-06-08 08:55

There is a JS function .charAt() you can use that to find the last digit

var num = 23.56
var str = num.toString();
var lastDigit = str.charAt(str.length-1);
alert(lastDigit);

查看更多
我只想做你的唯一
7楼-- · 2020-06-08 08:57

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.

查看更多
登录 后发表回答