Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prevent automatic number conversion in JavaScript

I want to call a function parsing a number with some zeros at the left to string. But JavaScript is automatically changing the number base.

This is what I’m trying to do:

function printNum(num) {
    return num.toString()
}

console.log(printNum(00000100010))
//32776

console.log(printNum(0555))
//365

I’m expecting "100010" or "00000100010" and "555" or "0555". Is that possible?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because of how JavaScript works, a number that starts with 0 is base 12 (except for 0x, 0b, and 0o, bases 16, 2, and 8, respecitively). You can’t change that, that’s just the specification.

If you’re wanting to preserve the zeros, the simple way is to just pass in a string originally.

function printNum(num) {
    return num.toString()
}

console.log(printNum("00000100010"))
//00000100010

console.log(printNum("0555"))
//0555

You can also define your function to take in a length to pad 0’s to or a number of zeros to pad at the start.

function printNum(num, minLength) {
  return num.toString().padStart(minLength, "0");
}

console.log(printNum(100010, 11))
//00000100010

console.log(printNum(555, 4))
//0555
function printNum(num, prefixLength) {
  return "0".repeat(prefixLength) + num.toString()
}

console.log(printNum(100010, 5))
//00000100010

console.log(printNum(555, 1))
//0555
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading