使用javascript检查十进制数字是否等于.9

时间:2015-08-19 08:46:22

标签: javascript

想知道如何使用javascript检测小数位数?

var totalpages = {{$photos->totalphotoCount}} / {{$photos->photoCount}};
if(totalpages === to something like .9 in the decimals)
{
write a code here
}

2 个答案:

答案 0 :(得分:1)

试试这个:

if(totalpages.toString().match(/.*\.9/)) {
  ...
}

如果不匹配,则返回null

答案 1 :(得分:0)

您可以使用正则表达式,但如果您需要更高级的检查,可以添加这样的辅助方法

// count specifies how many decimals you want to return
function getDecimals(number, count) {
    var nString = number.toString();
    var decStartIndex = nString.indexOf(".") + 1;
    nString = nString.slice(decStartIndex, decStartIndex + count); 
    return Number(nString);
}

function myFunction() {
    var num = 123.2381456;
    var dec1 = getDecimals(num, 1); // returns 2
    var dec1 = getDecimals(num, 0); // returns 0
    var dec1 = getDecimals(num, 5); // returns 23814
}