[英]How to get Last digit of number
How to extract last(end) digit of the Number value using jquery.如何使用 jquery 提取 Number 值的最后(结束)数字。 because i have to check the last digit of number is 0 or 5. so how to get last digit after decimal point因为我必须检查数字的最后一位数字是 0 还是 5。所以如何获得小数点后的最后一位数字
For Ex.对于前。 var test = 2354.55
Now how to get 5 from this numeric value using jquery. var test = 2354.55
现在如何使用 jquery 从这个数值中得到 5。 i tried substr but that is only work for string not for Number format我试过substr但这仅适用于字符串而不适用于数字格式
Like if i am use var test = "2354.55";
就像我使用var test = "2354.55";
then it will work but if i use var test = 2354.55
then it will not.那么它会起作用,但如果我使用var test = 2354.55
那么它不会。
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: 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.然后只需传播它并弹出最后一个数字。
you can just convert to string你可以只转换为字符串
var toText = test.toString(); //convert to string
var lastChar = toText.slice(-1); //gets last character
var lastDigit = +(lastChar); //convert last character to number
console.log(lastDigit); //5
There is a JS function .charAt()
you can use that to find the last digit有一个 JS 函数.charAt()
您可以使用它来查找最后一位数字
var num = 23.56 var str = num.toString(); var lastDigit = str.charAt(str.length-1); alert(lastDigit);
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.转换为字符串并获取最后一位数字的问题在于它没有给出整数的百分位值。
Just in one line.就在一行。
const getLastDigit = num => +(num + '').slice(-1); console.log(getLastDigit(12345)) // Expect 5
toString()
converts number to string, and charAt()
gives you the character at a particular position. toString()
将数字转换为字符串,而charAt()
为您提供特定位置的字符。
var str = 3232.43; lastnum = str.toString().charAt( str.length - 1 ); alert( lastnum );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.