I have a very strange issue using the Javascript remainder (or Modulus) operator.
I have a requirement to get the entire width of a board (excluding margins) and then make sure the setWidth
value fits directly into the area left.
This means that in the example below the remainder when area
is divided by setWidth
the result should be 0
.
Javascript Code :
var totalWidth = parseFloat('519');
var setWidth = parseFloat('101.6');
var leftMargin = parseFloat('11');
var rightMargin = parseFloat('0');
var area = (totalWidth - leftMargin) - rightMargin;
console.log('area : ' + area);
//Incorrect Value given...
var modVal = area % setWidth;
console.log('modVal : ' + modVal);
//Correct value of 5...
var divisionVal = area / setWidth;
console.log('divisionVal : ' + divisionVal);
The reason I am parsing the values from strings is because they are actually retrieved from textboxes on the page.
In my Example JSFiddle I have two different examples, one works as I expect, but the other does not. The only difference is the numbers.
In my example above the values should be as follows :
area = (519 - 11) - 0; //Should be 508 (and is)
modVal = 508 % 101.6; //Should be 0 (But isn't for some unknown reason)
divisionVal = 508 / 101.6; //Should be 5 (and is)
If anyone can explain to me why one of my examples works and the other doesn't then I'd be happy to hear it. But at the moment I just cannot understand why this doesn't work...
Any ideas?