pad number with leading zeros in js

How to Pad Number with Leading Zeroes in JavaScript

JavaScript allows you to easily work with numbers and strings. Sometimes you may need to pad a number with leading zeroes in case you need to treat as a string, or a fixed-width number in your code. In this article, how to easily pad number with leading zeroes in JavaScript.


How to Pad Number with Leading Zeroes in JavaScript

Every JS string variable has a built-in function padStart() available out of the box that you can use to pad numbers. Here is a simple example to pad leading zeroes to number so that its length is 4.

n = 9;
String(n).padStart(4, '0'); // '0009'

The above function padStart() accepts 2 arguments – length of the final string after padding, and the character to be used for padding.

If you want to pad number with $ sign instead of 0, just mention it as second argument.

n = 9;
String(n).padStart(4, '$'); // '$$$9'

On the other hand, if you want to pad number with trailing zeroes, you can use padEnd() function.

n = 9;
String(n).padEnd(4, '0'); // '9000'

The above function padEnd() accepts 2 arguments – length of the final string after padding, and the character to be used for padding.

In this article, we have learnt how to pad number with leading zeroes as well as trailing zeroes using JavaScript.

Also read:

How to Get Random Element from Array in JavaScript
How to Simulate Keypress in JavaScript
How to Call Function Using Variable Name in JavaScript
How to Detect Tab/Browser Closing in JavaScript
How to Include HTML File in Another HTML

Leave a Reply

Your email address will not be published. Required fields are marked *