e.g.,
var myNum = 1.208452
我需要获取小数点后的最后一位数字,即(2)
e.g.,
var myNum = 1.208452
我需要获取小数点后的最后一位数字,即(2)
你可以像这样试试:
var temp = myNum.toString();
var lastNum = parseInt(temp[temp.length - 1]); // it's 2
编辑
如果你想检查你的数字是否是实际的十进制数,你可以这样做:
var temp = myNum.toString();
if(/\d+(\.\d+)?/.test(temp)) {
var lastNum = parseInt(temp[temp.length - 1]);
// do the rest
}
如评论中所指出的,我最初误解了你的问题,并认为你想要小数点后的第一个数字,这是这个一行代码所做的事情:
result = Math.floor((myNum - Math.floor(myNum)) * 10);
如果您想要一个纯数学解决方案,以便在小数点后得到最后一位数字,您可以对该数字进行转换,直到最后一位数字成为小数点后的第一位数字,然后再使用上面的代码,就像这样(但它不再是一个漂亮的一行代码):
temp = myNum;
while( Math.floor(temp) != temp ) temp *= 10;
temp /= 10;
result = Math.floor((temp- Math.floor(temp)) * 10);
工作原理:
以上代码将temp乘以10,直到小数点后面没有数字为止,然后除以10得到只有一位小数的数字,然后使用原始代码来给出小数点后第一位数字!哇!
var regexp = /\..*(\d)$/;
var matches = "123.456".match(reg);
if (!matches) { alert ("no decimal point or following digits"); }
else alert(matches[1]);
这是如何工作的:
\. : matches decimal point
.* : matches anything following decimal point
(\d) : matches digit, and captures it
$ : matches end of string
只需这样做:
function lastdigit(a)
{
return a % 10;
}
/\..*(\d)$/
这样的东西吗? - user663031myNum=100
呢? - Tomas Ramirez Sarduy