Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript convert bigInt to string

I am trying to convert the following big int to a string in javascript with no success. My goal would end up with '582235852866076672'

var foo = 582235852866076672;
console.log(foo); // 582235852866076700

var baz = "'" + 582235852866076672 + "'";
console.log(baz); // '582235852866076700'

var emptyString = 582235852866076672+'';
console.log(emptyString); // 582235852866076700

var n = foo.toString();
console.log(n); // 582235852866076700

I figured the number was too big and was loosing precision as a result. I included the bigint library with no success:

var bigint = require('bigint');
var bigintLibrary = bigint(582235852866076672).toString();
console.log(bigintLibrary); //582235852866076700

The method toSting in the bigint library states:

"Print out the bigint instance in the requested base as a string."

I appreciate all help and comments. Thanks.

like image 740
srm Avatar asked Mar 29 '15 19:03

srm


1 Answers

As of 2019, you can use the built-in BigInt and BigInt literal, first, do something like:

// Cast to BigInt:
var result = BigInt("1234567801234567890");
result = BigInt(1234567801234567890);

// Or use BigInt literal directly (with n suffix).
result = 1234567801234567890n

Then use built-in toString method:

console.log('my BigInt is', result.toString());

See documentation on MDN

like image 98
studentmain Avatar answered Sep 17 '22 16:09

studentmain