39

I need to convert a string to BigInt like BigInteger in Javascript

Example

var reqId = "78099864177253771992779766288266836166272662";
var result = parseInt(reqId);
document.write(result);

Resultant value not matching since JavaScript only allows integers up to (2^53)-1.

Is there any way to overcome this?

2
  • I see no java here... why do you tag this as a java question?? Commented Apr 24, 2016 at 17:53
  • How to use that other packages to do Infinite precision, do u have any idea ? Commented Apr 24, 2016 at 17:53

4 Answers 4

64

BigInt is now a native JavaScript language feature. It's at Stage 3 in the TC39 process and it's shipping in V8 v6.7 and Chrome 67.

To turn a string containing a valid numeric literal into a BigInt, use the global BigInt function:

const string = '78099864177253771992779766288266836166272662';
BigInt(string);
// 78099864177253771992779766288266836166272662n

If you just want to hardcode the numeric value into your code, there is no need to convert from a string; use a BigInt literal instead:

const value = 78099864177253771992779766288266836166272662n;
Sign up to request clarification or add additional context in comments.

1 Comment

@Centell, That's because you're using a numeric literal instead of a string literal. The moment the non-BigInt numeric literal is created, you've already lost precision. See v8.dev/features/bigint#api
5

You can use a JavaScript lib called BigInteger.js for the purpose.it is an arbitrary-length integer library for Javascript, allows arithmetic operations on integers of unlimited size, notwithstanding memory and time limitations.This lib can be download from this link.Like var largeNumber = bigInt("75643564363473453456342378564387956906736546456235345"); You can find documentation of lib here https://www.npmjs.com/package/big-integer

Comments

1

You can use mathjs:

var reqId = "78099864177253771992779766288266836166272662";
var myBigNumber = math.bignumber(reqId);
var res = math.add(myBigNumber, 1);
console.log(myBigNumber.toString());
// 7.8099864177253771992779766288266836166272662e+43
console.log(res.toString());
// 7.8099864177253771992779766288266836166272663e+43

Comments

0

There are various ways of creating a BigInt, in this jskata you can see them and try it out https://jskatas.org/katas/es11/language/bigint/basics/#creating-one-can-be-done-in-multiple-ways

      const fourtyTwoAsBigInt = 42n;
      assert.strictEqual(BigInt("42"), fourtyTwoAsBigInt);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.