Explain Codes LogoExplain Codes Logo

Pad a number with leading zeros in JavaScript

javascript
prompt-engineering
functions
polyfills
Alex KataevbyAlex Kataev·Sep 22, 2024
TLDR

Here's the quick and dirty way to pad a number with leading zeros in JavaScript using the .padStart() method:

let num = 7; let paddedNum = num.toString().padStart(4, '0'); console.log(paddedNum); // "0007"

It ensures a string length of 4, padding with '0' if necessary.

Unfolding the magic of padStart

Looking for a crisper, cleaner solution? ES6 provides a more sleek syntax:

// Because arrow functions are cool! const padNumber = (num, width) => `${num}`.padStart(width, '0'); console.log(padNumber(5, 3)); // "005"

The padNumber function showcases the elegance and efficiency of ES6 by padding a number to a specified width with '0'.

Crafting custom solutions

Polyfill: The safety net

Not all environments support ES2017. Here's a polyfill for padStart:

if (!String.prototype.padStart) { String.prototype.padStart = function padStart(targetLength,padString) { targetLength = Math.max(targetLength, this.length); // Who needs if else when you have logical OR! padString = padString || '0'; let toPad = targetLength - this.length; return padString.repeat(toPad) + this; }; }

DIY padding: Build your own

Want to forge your own path? Try crafting a function, padDigits:

function padDigits(number, targetLength) { let str = number + ''; // While there's room, shovel in some zeros while (str.length < targetLength) { str = '0' + str; } return str; }

The padDigits function manually piles up zeros where needed.

Adventurous padding techniques

Array of Hope

For padding, JavaScript arrays present an interesting approach:

function padWithArray(n, width) { // Craft an Array, it's a charm! return new Array(width - String(n).length + 1).join('0') + n; }

This flexible approach uses arrays to build a string of zeros and then blend it with the number.

Slice 'n Dice

Hey string-lovers, slice your way to precision:

function padWithSlice(n, width) { let zeros = new Array(width).join('0'); return (zeros + n).slice(-width); }

This comes in handy when dealing with dynamic-length numbers, focusing on the width of the number itself.

Be a test-driven coder

Testing is essential to ensure your solution works in all JavaScript environments. Use tools like transpilers or polyfills for compatibility with older browsers or server-side JavaScript.

Be the master of your code, not the other way around!