Comparison of Calculation on BigNumber and Number in Javascript

181


MAX_SAFE_INTEGER
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER

stackoverflow:-

Requirement to match in PHP

v=(v = (num1* num2)/1000;num2)/1000; v = sqInfo($v); // precision safe till 15 digit
PHP code : https://bit.ly/3xfQ8JN



var a = BigInt(2472648273);
var b = BigInt(2344444444);

console.log("Calculate with type Big Int");
calculate(a,b,'mul',1000); // with big Int

console.log("Calculate without type Big Int");
var n1 = 2472648273;
var n2 = 2344444444;

calculate(n1,n2,'mul',1000); // without big Int

function calculate(num1,num2,operator,fraction) {
    var output;
    switch (operator) {
        case "add":
          output = num1 + num2;
          break;
        case "sub":
          output = num1 - num2;
          break;
        case "mul":
          output = num1 * num2;
          break;
        case "div":
          output = num1 / num2;
          break;
        default:
            output = 0;
            break;
    }
    console.log("output after operation : ");
    console.log(output);
    if(output > Number.MAX_SAFE_INTEGER) {
        console.log("Number is not safe");
        if(fraction >0 && typeof output === 'bigint') {
            output = output/BigInt(fraction);
        } else {
            console.log("output type in not big Int");
            output = output/fraction;
        }
    }
    else {
        console.log("Number is safe");
        if(fraction >0) {
            output = Number(output);
            output = output/fraction;
        }
    }
    console.log(output);
    console.log(output.toString()); // remove appended n from BigInt
}
 

OUTPUT

Calculate with type Big Int
output after operation :
5796986505601045212n
Number is not safe
5796986505601045n
5796986505601045

Calculate without type Big Int
output after operation :
5796986505601046000
Number is not safe
output type in not big Int
5796986505601046
5796986505601046