Modulo in JavaScript - large number

前端 未结 6 1862
情深已故
情深已故 2021-01-07 20:39

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 = 21050170         


        
6条回答
  •  南笙
    南笙 (楼主)
    2021-01-07 21:36

    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;
    }
    

提交回复
热议问题