如何在JavaScript算术运算中检测数字上溢/下溢?

时间:2014-04-19 01:22:16

标签: javascript

我今天正在进行编码测试,目标是在JavaScript中添加2个字符串整数表示时捕获所有边缘情况。我无法得到的一个案例是如何检测存储在IEEE 754数字中的总和的上溢/下溢。

通常,在C中,我会查看数字的二进制表示,但在JavaScript中,我只能查看32位的整数值。

这是我的代码:

function string_add(a, b) {
    if (arguments.length !== 2)
        throw new Error('two arguments expected as input');

    // ensure we have strings
    if (typeof a !== 'string' || typeof b !== 'string')
        throw new Error('bad parameter types');

    // ensure we do not have empty strings
    if (a.length === 0 || b.length === 0)
        throw new Error('an empty string is an invalid argument');

    // ensure we have integer arguments
    if (0 !== (+a % 1) || 0 !== (+b % 1))
        throw new Error('expected numeric integer strings for arguments');

    var sum = +a + +b;      // create numeric sum of a and b.
    sum+='';                // convert numeric sum to string
    return sum;
}

提前致谢。

1 个答案:

答案 0 :(得分:3)

实际上,由于浮点数学的工作方式,Javascript中的整数是53位信息。

我最后一次需要做类似的事情......

var MAX_INT = Math.pow(2, 53);
var MIN_INT = -MAX_INT;

var value = MAX_INT * 5;
if (value >= MAX_INT) {
  alert("Overflow");
}

// Note. you have to use MAX_INT itself as the overflow mark because of this:
value = MAX_INT+1;
if (value > MAX_INT) {
  alert("Overflow test failed");
}

编辑在考虑之后,会更容易说:

var MAX_INT = Math.pow(2, 53) -1;
var MIN_INT = -MAX_INT;

因为那是你知道的最大的INT没有溢出。