Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript precision while dividing

Is there a way to determine whether dividing one number by another will result in whole number in JavaScript? Like 18.4 / 0.002 gives us 9200, but 18.4 / 0.1 gives us 183.99999999999997. The problem is that both of them may be any float number (like 0.1, 0.01, 1, 10, ...) which makes it impossible to use the standard function modulo or trying to subtract, and floating point precision issues mean we will sometimes get non-whole-number results for numbers that should be whole, or whole-number results for ones that shouldn't be.

like image 290
arahusky Avatar asked Jan 18 '26 21:01

arahusky


2 Answers

One hacky way would be

  1. Convert both numbers to strings with toString()
  2. Count the precision points (N) by stripping off the characters before the . (including the .) and taking the length of the remaining part
  3. Multiply with 10^N to make them integers
  4. Do modulo and get the result

Updated Demo: http://jsfiddle.net/9HLxe/1/

function isDivisible(u, d) {
    var numD = Math.max(u.toString().replace(/^\d+\./, '').length, 
                        d.toString().replace(/^\d+\./, '').length);
    u = Math.round(u * Math.pow(10, numD));
    d = Math.round(d * Math.pow(10, numD));
    return (u % d) === 0;
}
like image 156
techfoobar Avatar answered Jan 20 '26 10:01

techfoobar


I don't think you can do that with JavaScript's double-precision floating point numbers, not reliably across the entire range. Maybe within some constraints you could (although precision errors crop up in all sorts of -- to me -- unexpected locations).

The only way I see is to use any of the several "big decimal" libraries for JavaScript, that don't use Number at all. They're slower, but...

like image 22
T.J. Crowder Avatar answered Jan 20 '26 10:01

T.J. Crowder