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?
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?
Share Improve this question edited Mar 14 at 14:53 TylerH 21.1k78 gold badges79 silver badges114 bronze badges asked Jan 5, 2019 at 8:17 qadenzaqadenza 9,30118 gold badges78 silver badges144 bronze badges 2-
1
Numbers do not have a
padStart
method. – CertainPerformance Commented Jan 5, 2019 at 8:17 - It's a string method, so if you want to use it, cast the number to a string. – CertainPerformance Commented Jan 5, 2019 at 8:21
4 Answers
Reset to default 20The 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)
Convert your value from int
to String
just like this int.toString().padStart(n, '0');
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) ;
Since padStart()
is not patible 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