简体   繁体   中英

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.

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM