VIKAS KOHLI
VIKAS KOHLI

Reputation: 8470

How to handle very big numbers in node js?

I am using BigInt(20) datatype for auto Increment id in mysql database. and when the integer value is so big then how can I handle this as after the number precision of javascript, it won't to allow to insert and read any number Value. So how can I achieve this. Read about the big-integer libraries but I won't the expected result

Example:-

var x = 999999999999999999999999999999999999999;

How can I print the same number without using its exponential value and any garbage value ?

I tried like that

var BigNumber = require('big-number');

var x = new BigNumber(999999999999999999999999999999999999999, 10);
console.log(x);

Example2:-

If I get the last inserted Id, then how can I handle this value

 connection_db.query('INSERT INTO tableName SET ?', tableData, 
  function (error1, results1, fields1) {
     error1){
         // Db error
        }else{
         var lastInserted = new BigNumber(results1.insertId);
         console.log(lastInserted);// still wrong value
          }

  });

Upvotes: 1

Views: 8571

Answers (1)

robertklep
robertklep

Reputation: 203519

You can only pass/show large numbers like that as strings:

var BigNumber = require('big-number');

var x = new BigNumber('999999999999999999999999999999999999999', 10);
console.log(x.toString())

However, in the end, it's up to the MySQL driver how it handles large numbers like this, because it does have to take into account Number.MAX_SAFE_INTEGER.

For instance, the mysql module has various options (supportBigNumbers and bigNumberStrings) that relate to handling BIGINT.

Upvotes: 3

Related Questions