DEV Community

Wojciech Wernicki
Wojciech Wernicki

Posted on • Originally published at wojciech.space on

Add leading zeros to a number in JavaScript

Add leading zeros to a number in JavaScript

As I was looking for a more subtle solution for inserting leading zeros to a number than if (number < 10) return `0${number}`;, I found this answer on StackOverflow, which I want to expand to near-one line code snippet.

TypeScript:

// pad-number.ts
const padNumber = (number: number, leadingZeros: number): string => {
  return `${number < 0 ? "-" : ""}${String(Math.abs(number)).padStart(leadingZeros, '0')}`;
}
Enter fullscreen mode Exit fullscreen mode

JavaScript:

// pad-number.js
const padNumber = (number, leadingZeros) => {
  return `${number < 0 ? "-" : ""}${String(Math.abs(number)).padStart(leadingZeros, '0')}`;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)