0

I have two inputs #input_a and #input_b with decimal:

<input id="input_a" name="input_a" step="any" type="number">
<input id="input_b" name="input_b" step="any" type="number">

<a href="javascript:checkForm();">Save</a>

and js:

function checkForm(i){
    var a = $('input#input_a').val().replace(',','.');
    var b = $('input#input_b').val().replace(',','.');
    var send = true;

    if(parseFloat(a) % parseFloat(b) != 0){
        $('#formerror).html('Invalid');
        send = false;
    }

    if(send==true) {
        $('#form').submit();
    }
}

but for example for values input_a = 2, input_b = 0.1

parseFloat(a) % parseFloat(b) = 0.09999999999

and give me an error. How to do it this well?

Nips
  • 13,162
  • 23
  • 65
  • 103

2 Answers2

1

JavaScript uses binary floating point representations of numbers. As a result of this, the internal representation 0.1 is only an approximation of the decimal value. This is the same reason that 0.1 + 0.2 yields 0.30000000000000004.

So while 2 is divisible by 0.1, it isn't perfectly divisible by the runtime's internal approximation of 0.1.

One way around this would be to check for very close divisors, rather than perfect divisors:

// note +value is shorthand for parseFloat(value)
var a = +$('input#input_a').val().replace(',','.'), 
    b = +$('input#input_b').val().replace(',','.'),
    epsilon = 1e-10, // some very small value
    mod = a % b;

if(mod < epsilon || b - mod < epsilon){
    $('#form').submit();
} else {
    $('#formerror).html('Invalid');
}
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
0

Check out this answer:

https://stackoverflow.com/a/2925496/2956903

It actually is for C# but I think the same could apply to your example.

So the answer is:

There is no error. Floating point arithmetic just does not offer more precision.

Community
  • 1
  • 1
Jonas
  • 1,315
  • 1
  • 18
  • 31