2

My script calculates weights of products. Full box weights 25.2KG. Each item weights 4.2KG making 6 items full box.

I'm chekcing with Javascript if box.

   alert(jsonData.total_weight  + ' % ' +  fullpackweight + ' = ' + jsonData.total_weight % fullpackweight);
if(jsonData.total_weight % fullpackweight == 0) {
    $('#fill_status').hide();
    $('#fill_status i').html('OK ' + jsonData.total_weight);
} else { 
    $('#fill_status').show();
    $('#fill_status i').html('NOT OK ' + jsonData.total_weight);
}

Alert box from top of script gives following results:

25.2 % 25.2 = 0
50.4 % 25.2 = 0
75.6 % 25.2 = 25.199999999999996 (WHY?)
100.8 % 25.2 = 0
126 % 25.2 = 3.552713678800501e-15 (WHY?)

Anyone whou could explain this behaviour?

Grzegorz
  • 3,538
  • 4
  • 29
  • 47
  • 3
    http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken And [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Moritz Roessler May 23 '13 at 09:13
  • Scale those values, do the modulo and scale them down again – Moritz Roessler May 23 '13 at 09:15
  • tl;dr: Yes, it's broken but so is in every language, and a fix would be very expensive. Floats are inherently unprecise. – John Dvorak May 23 '13 at 09:15
  • @C5H8NNaO4 won't help. They should never be downscaled and upscaled – John Dvorak May 23 '13 at 09:16
  • 1
    And the easier read http://floating-point-gui.de/ – slobodan.blazeski May 23 '13 at 09:16
  • @JanDvorak it should work up to a precision of 2^53 (scaled), whether it should be done or not is another point =). The best you could do is do the Math in grams not in Kilograms (avoiding floats at all) – Moritz Roessler May 23 '13 at 09:22
  • lol. System is written to store everything as KGs. Would be better to store as grams and format output as KG. For now doing number * 100 and round for comparision. – Grzegorz May 23 '13 at 09:40

1 Answers1

1

The problem is that you use float instead of integer for modulo.

75.6 % 25.2 = 25.199999999999996

BUT

756 % 252 = 0

So conversis to integer (by using *10) will solve your problem.

Check this

25.199999999999999 - 25.2

It will give you 0 :D

tkeram
  • 214
  • 1
  • 5
  • Indeed. Did like it. Except multiplied by 100 and rounded value since first value rounded gave me 7559.99999. Better stick to measure weight in grams :) – Grzegorz May 23 '13 at 09:24
  • Not sure multiplication by ten always converts to an integer. Why should it? – John Dvorak May 23 '13 at 09:46
  • in javascript typeof 25.2 and typeof 252 is in both cases numeric, so you doesn't have pure integer or float type like in C# or Java – tkeram May 23 '13 at 09:50