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 do I retain leading zeroes in an Integer/Number in JavaScript?

I am trying to retain leading zeroes in an integer/number within JavaScript.

In this example I have an "ItemName" key which has either a string or an integer as its value.

I only want to have integers to be the value, but when I try converting any string value to a number, it will remove the leading zeroes.

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

I need to retain the zeroes so that the data sent will reliably be 6 digits, where in the example it would only be 4 digits.

The value is intended to be an identifier for a given Item.

{"Item": [{"ItemName":"007730","BusinessUnit":1}] } 
{"Item": [{"ItemName":917730,"BusinessUnit":1}] }

This is for my work and we use ES6, but if there’s an option outside of that, I’m certainly open to it.
Thanks in advance!

>Solution :

You can’t have a number with leading zeroes in Javascript, because, as Randy Casburn said, they don’t have any value. You have to convert it to a string and use String.padStart() to pad the string with zeroes. parseInt will work with leading zeroes. For example:

(294).toString().padStart(6, "0") --> "000294"


parseInt("000294") --> 294

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