Kuan
Kuan

Reputation: 11389

how to split a large integer in javascript

All:

How can I correctly turn a VERY VERY LARGE number(at least 32 digits) into a character array?

For example:

var n = 111111122222233333334444444445555555555666666677777777788888888888

Thanks,

Upvotes: 0

Views: 1943

Answers (3)

kyle
kyle

Reputation: 691

If you're dealing with very large numbers in javascript (anything greater than Number.MAX_SAFE_INTEGER) you'll have to handle the number differently than you would a normal integer.

Several libraries exist to help aid in this, all of which basically treat the number as a different type - such as a string - and provide custom methods for doing various operations and calculations.

For example, if you only need integers you can use BigInteger.js. Here's an implementation below:

const bigInt = require("big-integer")

const largeNumber = bigInt(
  "111111122222233333334444444445555555555666666677777777788888888888",
)
const largeNumberArray = largeNumber.toString().split('')

Also check out some other stackoverflow questions and resources regarding handling big numbers in Javascript:

npm's big-number-> https://www.npmjs.com/package/big-number

What is the standard solution in JavaScript for handling big numbers (BigNum)?

Extremely large numbers in javascript

What is the standard solution in JavaScript for handling big numbers (BigNum)?

http://jsfromhell.com/classes/bignumber

http://www-cs-students.stanford.edu/~tjw/jsbn/

Upvotes: 1

pretzelhammer
pretzelhammer

Reputation: 15105

You can get the string representation of a number by calling toString and then convert it to a character array using Array.from.

var number = 123456789;

console.log(Array.from(number.toString()));

var bigNumber = "34534645674563454324897234987289342";

console.log(Array.from(bigNumber));

Upvotes: 1

Bing
Bing

Reputation: 3171

If you aren't breaking the maximum integer value for JavaScript, then you can use:

var n = 123456789;
var l = n.toString().split('');

That will get you an array where the first value is the 1 character, the second is the 2, etc.

Upvotes: 0

Related Questions