CuteMachine

How To Pad A Number With Leading Zeros In JavaScript

In this JavaScript article, you will learn how to pad a number with leading zeros (or any other character).

Imagine you program a game and need to display the player's score like this.

000001
000002
000003
// … well, you get the idea.

Writing Our Own Padding Function

Writing a function that pads a number or string with a particular character is not that difficult.

function padLeft(num, length, char = '0') {
    let string = typeof(num) === 'number' ? String(num) : num
    
    while (string.length < length) {
        string = char + string
    }
  
    return string
}

const score = 4321
padLeft(score, 6)    // '004321'

const IBAN = "2345"
padLeft(IBAN, 12, '*')    // '********2345'

We can use the padLeft() function to create our score label.

Another application would be to cloak a banking number where you only want to show the last digits.

Using Lodash's padStart() function

As usual, Lodash offers an excellent solution to our problem.

import padStart from 'lodash/padStart'

const score = 4321

padStart(score, 6, '0')    // '004321'

Filling A String With String.padStart()

In ES2017 two methods have been added to the String object, padStart() and padEnd(). We can use the padStart() to show our score with leading zeros.

const score = 4321
String(score).padStart(6, '0')    // '004321'

Conclusion

JavaScript is getting better with each release. More and more functions from Libraries like Underscore and Lodash are not needed anymore because they are included in the ECMAScript standard itself.

Posted on CuteMachine.

Jo's Profile ImageWritten by Jo who lives and works in Frankfurt building digital doodah. Stalk him on Twitter.

TOS • Privacy • Disclaimer