Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript-如何获取十进制数后的最后一位数字?_Javascript - Fatal编程技术网

Javascript-如何获取十进制数后的最后一位数字?

Javascript-如何获取十进制数后的最后一位数字?,javascript,Javascript,e、 g 我需要得到小数点后的最后一位myNum,因此它是(2)您可以尝试以下方法: var myNum = 1.208452 编辑 您可能希望检查您的数字是否为实际小数,您可以执行以下操作: var temp = myNum.toString(); var lastNum = parseInt(temp[temp.length - 1]); // it's 2 这种方法: var temp = myNum.toString(); if(/\d+(\.\d+)?/.test(temp)) {

e、 g


我需要得到小数点后的最后一位myNum,因此它是(2)

您可以尝试以下方法:

var myNum = 1.208452
编辑

您可能希望检查您的数字是否为实际小数,您可以执行以下操作:

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
}
工作原理:

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
如果你想要一个纯数学的解决方案,给出小数点后的最后一个数字,你可以变换数字,直到最后一个数字是小数点后的第一个数字,然后使用上面的代码,就像这样(但它不再是一个好的一行):

工作原理:

上面的代码将temp乘以10,直到小数点后没有任何值,然后除以10,得到一个小数点后只有一位的数字,然后使用我的原始代码给出小数点后的第一位数字!呸

只要做:

temp = myNum;
while( Math.floor(temp) != temp ) temp *= 10;
temp /= 10;
result = Math.floor((temp- Math.floor(temp)) * 10);

你试过类似于
/\..*(\d)$/
的东西吗?我是初学者,所以我不知道如何应用它。有样品或参考品吗?如果没有小数点怎么办?如果myNum=100怎么办?谢谢。您的代码对其他方法很有帮助。谢谢,非常感谢:)lastdigit(1.2)的结果将是1.2,而不是像OP saidOk那样的2不适用于小数,但适用于整数
temp = myNum;
while( Math.floor(temp) != temp ) temp *= 10;
temp /= 10;
result = Math.floor((temp- Math.floor(temp)) * 10);
function lastdigit(a)
{
    return a % 10;
}