JavaScript add 0 before number tips

avatar
Mofei Zhu

A friend who often processes financial data may encounter a need to convert a string of a fixed length to a fixed length, such as 123 => 000123.

Usually we will try this:

let num = 123;
// convert the value to a string
let numStr =  num.toString();
let strLen = 5;
// Calculate the difference of 0 vacancies
let spaceLen = strLen - numStr.length;

// spell out these 0
let spaceStr = '';
for(let i=0; i<spaceLen; i++){
    spaceStr += '0';
}

// Add the spelled 0 and the original numeric string
let result = spaceStr + numStr;

In this, we try to convert the number into a string, then calculate the length of the string, generate the missing 0 string, and assemble it together.

But! In fact, we can use only use one line of code to solve this problem:

('00000' + 123).slice(-5)

In this scenario, we first try to use our agreed number (5) of 0 strings plus our numbers to form a new string 00000123, and then use slice to intercept the length we need from the end of the string (5), then we can get the value we want.

https://zhuwenlong.com

Although this method is simple, there is one point that needs to be reminded that in the actual production environment we must consider the case where the value length is greater than the length we have agreed to (12312214124=>214124).