How to get missing leading zero while conversion of number to string in javascript

In this tutorial I will discuss about how to get missing leading zero while conversion of number to string in javascript. I have faced this problem today and at that time i thought to share with you people so that you can save your half hour that i have wasted today for solving this problem :)

How to get missing leading zero while converting number to string in javascript

Today while developing the countdown module, i got a requirement to show the days value which was a number like 01,02,03,04.... up to 30, in two different spans in such a way that the leading 0 of 01 value should be shown in first span and then 1 in second span, likewise if we have 21 as a value then 2 will be shown in first span and 1 will be shown in second span. I Just want to clear your confusion, in my example the value of days variable change dynamically when countdown start. I was very much amazed when i saw the conversion of number 01 to string resulting in only 1, the conversion of number 02 to string resulting in only 2, and then suddenly i thought where is leading zero???
<script language="javascript" type="text/javascript">
var days=01;
var daysString=Number(days);
daysString=daysString.toString();
n1=daysString.substring(0,1);
n2=daysString.substring(1,2);
alert(n1);//it should give you 0 but it will give you 1
alert(n2);//It should give you 1 but it will give you nothing
</script>

So to solve this problem and get missing leading zero, you have to follow the example given below
<script language="javascript" type="text/javascript">
var days=01;
var daysString=Number(days);
daysString=daysString.toString();
if(daysString.length>1)
{
n1=daysString.substring(0,1);
n2=daysString.substring(1,2);
}
else if(daysString.length==1)
{
n1="0";
n2=daysString.substring(0,1);
}
else
{
n1="0";
n2="0";
}
alert(n1);//Now it will give you 0
alert(n2);//Now it will give you 1
</script>

The variable days store integer(Number, Numeric) value that comes dynamically, that's why the value is not surrounded by any " ". If days="01" then there was no problem by getting 01 as a 0 and 1 because any thing inside the double quotes is called string and we can get substring easily from string.

I know this tutorial is a bit technical but you will find this very much handy.

Thanks and Keep in touch.

0 comments: