JavaScript convert leading zero number to string or array?

Viewed 374

Normally we can easily convert a number string using toString() method or concat '' with it. But when number with leading zero like 01010 I can't convert it to plain string like (01010).toString()

Also how can I convert it to string? Number is 01010 expected output '01010'

How to convert leading zero number to array in JavaScript? Number is 01010 expected output [0,1,0,1,0]

2 Answers

You have to put the radix (i.e. the base system of the given number) in Number.prototype.toString method. By default any number starting with a 0 is assumed octal (base 8). So go like this:

(01010).toString(8)

Because of the leading 0 the number is parsed as an octal (base 8).

  • You can convert to base 8 using array#toString and add back the leading 0.
  • From there you can use array#split to convert into an array.

Convert to base 8 and re-add leading 0:

"0" + 01010.toString(8) //> "01010"

Split string into array items:

("0" + 01010.toString(8)).split("") //> ["0", "1", "0", "1", "0"]

Demo:

function octalToArray(octal) {
  return ("0" + octal.toString(8)).split("")
}

console.log(octalToArray(01110))
console.log(octalToArray(01110010))

Related