Search code examples
javascriptintegermodulo

Modulo in JavaScript - large number


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

Whats the problem here?

Regards, Benedikt


Solution

  • 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) {
      let cDivident = '';
      let cRest = '';
    
      for (let i in divident) {
        let cChar = divident[i];
        let 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;
    }