javascript – How can I add leading zeros to an integer?

Question:

I receive an integer, for example 3, and I want to display a string such as "0000003" (six "0" and "3"). Or receive the 1050 and display "0001050" (three "0" and the number).

So what I want is to show a 7-digit integer to which to add a number, showing the remaining 0's.

var numero = 3;
var cadenaNumerica = 0000000;
var resultado = numero + cadenaNumerica;
//Lo que necesito que devuelva resultado 0000003

Answer:

ECMA Script 2017 includes -finally- a function to do it: padStart()

The syntax is:

str.padStart (size [, string_with_which_padding])

Where:

  • tamaño is the size of the resulting string.
  • cadena_con_la_que_hacer_padding is "" (a space) by default.

Therefore, you would do something like:

 var numero = '3'; resultado = numero.padStart(7, "0"); console.log(resultado);
Scroll to Top