1

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?

4

2 回答 2

3

modVal2.842170943040401e-14在这里给出,0.000000000000028421709430404010与浮点数差不多。

浮点运算可能很奇怪或难以处理。确保您消息灵通。

于 2013-10-30T16:53:35.230 回答
0

JavaScript 中的浮点数%非常奇怪:

在其余情况下,既不涉及无穷大,也不涉及零,也不涉及 NaN,被除数 n 和除数 d 的浮点余数 r 由数学关系 r = n - (d × q) 定义,其中 q是一个整数,仅当 n/d 为负时为负,仅当 n/d 为正时为正,并且其大小尽可能大而不超过 n 和 d 的真数学商的大小。r 使用 IEEE 754 舍入到最近模式计算并舍入到最接近的可表示值。

所以在这里,519 / 101.6是 5 多一点(它在 5 和 6 之间)。因此,在这种情况下,整数“q”是5,并且101.6 * 5508(几乎)。减法的结果是11.000000000000028

于 2013-10-30T16:56:36.810 回答