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]
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).
array#toString and add back the leading 0.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))