9
let m = 5;
m = m.padStart(2, '0');

Error:

m.padStart is not a function

Expecting result: 05;

I'm on Chrome, last version.

Any help?

qadenza
  • 9,025
  • 18
  • 73
  • 126

4 Answers4

15

The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start (left) of the current string.

It is a String function. Not a number function. Refer

Solution-

let m = '5';
m = m.padStart(2, '0');
alert(m)
ellipsis
  • 12,049
  • 2
  • 17
  • 33
  • and what IS method for numbers? – qadenza Jan 05 '19 at 08:21
  • You have to convert number to string. Refer--https://stackoverflow.com/questions/10073699/pad-a-number-with-leading-zeros-in-javascript – ellipsis Jan 05 '19 at 08:23
  • 2
    There seems to be a reason why `m` is a number, hence I would leave that as it is and call `.toString()` on it before calling `.padStart()`: `m.toString().padStart(2, '0')` – Andreas Jan 05 '19 at 08:47
  • node 14, and i still didn't have the prototype to chain it: m.toString(...).padString is not a function. typeof m === string – MTroy Nov 01 '20 at 19:41
11

Convert your value from int to String just like this int.toString().padStart(n, '0');

Zoren Konte
  • 306
  • 4
  • 12
1

change the number value to string , I was need this function to convert current hour value to leading zero number , your example should be

let m = 5+''; // just in case you can't change the actual number variable .
m = m.padStart(2, '0');

my code that i was need it

function CurrentTime(  ) {
 var today =  new Date();
  var h = today.getHours(  )+'' ; var m = today.getMinutes()+''   ;
 return  h.padStart( 2 ,  '0'  ) +':'+m.padStart( 2 ,  '0'  )  ; 
    }
 var current =  CurrentTime(  )   ;
 var timeNow = mydiv.innerText ; console.log("current: " + current)     ; 
Salem
  • 654
  • 7
  • 24
1

Since padStart() is not compatible with Internet Explorer (IE) and other old browser versions and if you try using it with numbers you can get:

let m = 5;
m = m.padStart(2, '0');
alert(m);

Uncaught TypeError: m.padStart is not a function at :2:7

Here I am to provide you a function that I created, it works fine with Strings as well as Numbers in case that somebody need something like that padding a Number to 01, 02, .. 09:

let m = 5;
m = padValue(m);
alert(m);

// Sam pading value to start with 0. eg: 01, 02, .. 09, 10, ..
function padValue(value) {
    return (value < 10) ? "0" + value : value;
}

As I mentioned you can replace assigned 5 value to 05:

let m = '5'; // The result will be 05

If you pass a value greater than 9 as String or Number will display the value without adding the padding. e.g.:

let m = '10'; // The result will be 10

Or

let m = 10; // The result will be 10
S. Mayol
  • 2,565
  • 2
  • 27
  • 34