最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check whether an integer is divisible by a decimal? - Stack Overflow

programmeradmin3浏览0评论

If use % then it works for integer%interger:

10%5 == 0 return true;
10%3 != 0 return false;

But how to use code to check whether variable a can

a%0.002 == 0 return true;
a%0.002 != 0 return false;

a could be integer or float.

Thanks in advance for any hint

If use % then it works for integer%interger:

10%5 == 0 return true;
10%3 != 0 return false;

But how to use code to check whether variable a can

a%0.002 == 0 return true;
a%0.002 != 0 return false;

a could be integer or float.

Thanks in advance for any hint

Share Improve this question asked Jun 4, 2013 at 2:54 DreamerDreamer 7,55127 gold badges108 silver badges198 bronze badges 2
  • By 'divisible by a decimal', you mean the quotient is an integer? Or do you mean if it returns a rational number? – user2416945 Commented Jun 4, 2013 at 2:56
  • Well, I just notice the question is very dumb, I just want to check a a result of the division(any number divided by decimal) is any integer, like Miky mentioned. – Dreamer Commented Jun 4, 2013 at 2:59
Add a ment  | 

3 Answers 3

Reset to default 7

You can use the modulo operator to verify the division results in an integer:

var n=25, dec=.0125;

(n/dec)%1==0; //   returned value: (Boolean) true


var n=25, dec=.022;

(n/dec)%1==0; //  returned value: (Boolean) false

First, divisibility is defined only for integers. So your statement is not necessarily mathematically correct.

Now, if you just want to see if a number can be expressed as an integer multiple of another decimal number, than the best way do do that is perhaps to implement a function that checks whether the result of the division is an integer.

In general, you can think of the % (modulo operator) as performing an integer division, and returning the remainder.

I think you need some custom function like

function test(a, b){
    var result = a / b;
    return Math.round(result) == result;
}
发布评论

评论列表(0)

  1. 暂无评论