Voltaire22
Voltaire22

Reputation: 23

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!

Upvotes: 1

Views: 6922

Answers (2)

user4617883
user4617883

Reputation: 1499

This can be done with Intl.NumberFormat like this:

const num = 7730;
const formattedNum = new Intl.NumberFormat('en', { minimumIntegerDigits: 6, useGrouping: false }).format(num);
console.log(formattedNum);

Upvotes: 1

user1280483
user1280483

Reputation: 560

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

Upvotes: 6

Related Questions