如何使用 jquery 提取 Number 值的最后一位(结束)数字。 因为我必须检查数字的最后一位数字是0还是5。那么如何获取小数点后的最后一位数字
对于前。
var test = 2354.55
现在如何使用 jquery 从这个数值中获取 5。
我尝试了 substr 但这仅适用于字符串,不适用于数字格式
就像我正在使用
var test = "2354.55";
然后它会起作用,但如果我使用
var test = 2354.55
那么它就不会。
这对我们有用:
var sampleNumber = 123456789,
lastDigit = sampleNumber % 10;
console.log('The last digit of ', sampleNumber, ' is ', lastDigit);
适用于小数:
var sampleNumber = 12345678.89,
lastDigit = Number.isInteger(sampleNumber) ? sampleNumber % 10
: sampleNumber.toString().slice(-1);
console.log('The last digit of ', sampleNumber, ' is ', lastDigit);
单击“运行代码片段”进行验证。
试试这个:
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);
ES6/ES2015 更新:
在数字不可迭代的情况下,我们可以使用标记模板。因此,我们需要将数字转换为它的字符串表示形式。然后将其展开并弹出最后一个数字。
你可以直接转换为字符串
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
.slice()
:
var test = 2354.55;
var lastDigit = test.toString().slice(-1);
//OR
//var lastDigit = (test + '').slice(-1);
alert(lastDigit);
就在一行。
const getLastDigit = num => +(num + '').slice(-1);
console.log(getLastDigit(12345)) // Expect 5
如果您想要数字在百分位,那么您可以执行以下操作:
test * 100 % 10
转换为字符串并获取最后一位数字的问题是它没有给出整数的百位值。
有一个JS函数
.charAt()
你可以用它来查找最后一位数字
var num = 23.56
var str = num.toString();
var lastDigit = str.charAt(str.length-1);
alert(lastDigit);
toString()
将数字转换为字符串,charAt()
为您提供特定位置的字符。
var str = 3232.43;
lastnum = str.toString().charAt( str.length - 1 );
alert( lastnum );
这对我有用,我们可以使用以下计算来代替将其转换为字符串
const getDigit = (number,place) =>{
return ((number % (10 * place)) - ((number % (10 * place)) % place)) / place
}
所以要获得我们将使用的数字的第 100 位
getDigit(1234567,100) // output 5