Explain Codes LogoExplain Codes Logo

How to output numbers with leading zeros in JavaScript?

javascript
prompt-engineering
functions
callbacks
Alex KataevbyAlex KataevยทJan 10, 2025
โšกTLDR

Use padStart() to lead numbers with zeros in quick time:

const num = 42; const result = num.toString().padStart(4, '0'); // Returns "0042", like a secret agent, but padded ๐Ÿ˜‰

Substitute 4 with your target length.

To handle negative numbers, consider the sign while padding:

const negNum = -42; const negResult = (`${negNum}`).replace( /^-/, '-' + Math.abs(negNum).toString().padStart(4, '0') ); // Returns "-0042", yes, negativity attracts zeros! ๐Ÿ˜„

Slice, dice, and pad numbers

In programming, essentials like edge cases should be at your fingertips. Here's how you can elegantly handle negative and decimal numbers while padding.

Negative numbers

Separate the sign and digits for negative numbers:

const negWithZeros = (number, width) => { const absNumber = Math.abs(number).toString().padStart(width, '0'); return number < 0 ? '-' + absNumber : absNumber; // Returns a padded absolute number with its original sign. };

Decimal numbers

For decimal numbers, pad their integer part preserving the fraction part:

const decimal = 3.14; const decimalWithZeros = decimal.toString().split('.'); decimalWithZeros[0] = decimalWithZeros[0].padStart(4, '0'); const fullDecimal = decimalWithZeros.join('.'); // "0003.14", not a pie anymore!

For the love of large numbers

For large numbers, slice and dice while padding:

const largeNumber = 12345678901234567890n; const paddedLargeNumber = largeNumber.toString().padStart(25, '0'); // "00012345678901234567890", becomes noticeable

Use loops and slices for custom padding

In case padStart is missing in action, go gaga over custom pad functions:

Custom zeroPad function

function zeroPad(number, width) { number = number.toString(); while (number.length < width) { number = '0' + number; // "0" here is like 'Coffee' for developers, serve till you reach 'production' ๐Ÿ˜„ } return number; }

Try slicing the pie

Create a large chain of zeros and slice it to desired size:

function zeroPadSlice(number, width) { return (new Array(width).join('0') + number).slice(-width); // A slice is always right, just like pizza! }

Have a plan B! Alternatives to padStart

If you're all about making your function bulletproof and backward compatible. Here are some alternative methods!

Extend Number object

You might have come across the Number prototype being extended:

Number.prototype.pad = function(width) { return this.toString().padStart(width, '0'); };

But remember the golden rule - extending native prototypes can backfire, kinda like eating a random mushroom in the wild. It's enticing but risky!

Meet zfill - Your new best friend

Python developers would recognize the hero named zfill, but here's how you can introduce it to JavaScript:

function zfill(number, width) { return (Array(width).join('0') + number).slice(-width); }