0

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,

Kuan
  • 11,149
  • 23
  • 93
  • 201
  • 2
    you can't - because your example is larger than `Number.MAX_SAFE_INTEGER` - note: in Chrome and Node you can `var n = 111111122222233333334444444445555555555666666677777777788888888888n; n.toString().split('')` - **not the *n* at the end of the number** – Jaromanda X Oct 19 '18 at 23:45
  • Where is the number coming from? Easiest solution would be to make it a string from the start if you can. – John Montgomery Oct 19 '18 at 23:49

3 Answers3

1

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));
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
1

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/

kyle
  • 691
  • 1
  • 7
  • 17
0

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.

Bing
  • 3,071
  • 6
  • 42
  • 81