JavaScript中的Modulo - 大量的 [英] Modulo in JavaScript - large number
问题描述
我尝试用JS'模数函数计算,但是得不到正确的结果(应该是1)。这是一段硬代码。
I try to calculate with JS' modulo function, but don't get the right result (which should be 1). Here is a hardcoded piece of code.
var checkSum = 210501700012345678131468;
alert(checkSum % 97);
Result: 66
这里的问题是什么?
问候,
Benedikt
Regards, Benedikt
推荐答案
Benedikt版本的一系列改进: cRest + =''+ cDivident;是一个错误修复; parseInt(divisor)可以将两个参数作为字符串传递;最后检查空字符串是否总是返回数值;添加了var语句,因此它不使用全局变量;将foreach转换为旧式,因此它适用于具有较旧Javascript的浏览器;修正了cRest == 0; bug(感谢@ Dan.StackOverflow)。
A bunch of improvements to Benedikt's version: "cRest += '' + cDivident;" is a bugfix; parseInt(divisor) makes it possible to pass both arguments as strings; check for empty string at the end makes it always return numerical values; added var statements so it's not using global variables; converted foreach to old-style for so it works in browsers with older Javascript; fixed the cRest == 0; bug (thanks @Dan.StackOverflow).
function modulo (divident, divisor) {
var cDivident = '';
var cRest = '';
for (var i in divident ) {
var cChar = divident[i];
var cOperator = cRest + '' + cDivident + '' + cChar;
if ( cOperator < parseInt(divisor) ) {
cDivident += '' + cChar;
} else {
cRest = cOperator % divisor;
if ( cRest == 0 ) {
cRest = '';
}
cDivident = '';
}
}
cRest += '' + cDivident;
if (cRest == '') {
cRest = 0;
}
return cRest;
}
这篇关于JavaScript中的Modulo - 大量的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!