Modulo in JavaScript - large number

前端 未结 6 1844
情深已故
情深已故 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:28

    For an IBAN calculation form a normal bankaccount number I end up with a very large number contained in a string datatype. From this large number I have to find the rest when divided by 97 -> large number % 97.

    As soon as I convert the datatype to an integer I get an overflow resulting in a negative integer and eventually a wrong rest value. As I saw some verbose pieces of code (which also gave wrong outcome), I could not resist to share my own. Credits go to Finding Modulus of a Very Large Number with a Normal Number

    modulo: function(divident, divisor) {
        var partLength = 10;
    
        while (divident.length > partLength) {
            var part = divident.substring(0, partLength);
            divident = (part % divisor) +  divident.substring(partLength);          
        }
    
        return divident % divisor;
    }
    

    N.B. I use 10 positions here as this is smaller than the 15 (and some) positions of max integer in JavaScript, it results in a number bigger than 97 and it's a nice round number. The first two arguments matter.

提交回复
热议问题