Em Sta
Em Sta

Reputation: 1706

JavaScript if number < 10 add a "0"

I made a simple countdown with JavaScript, here you can see an example: http://jsfiddle.net/PCwx8/

It simply counts to midnight today. My problem is that I simply want JavaScript to prepend a "0" to the numbers that are less than 10. I have an idea like:

if (i<10)
{
    i="0" + i;
 }
return i;

But I don't know whether it's an integral or simply a number? Thanks for the help, I normally have nothing to do with JavaScript, so please understand!

Upvotes: 1

Views: 423

Answers (5)

ZER0
ZER0

Reputation: 25322

Not sure what's the question is, however you can generalize with something like that:

function lead(str, num) {
    return (str + num).slice(-str.length);
}

function leadzero(num) {
    return lead("00", num);
}

console.log(leadzero(2)) // 02
console.log(leadzero(10)) // 10

Of course if you're in an environment that supports ECMAScript5's bind, leadzero can be done in this way:

var leadzero = lead.bind(null, "00");

Upvotes: 0

Ben McCormick
Ben McCormick

Reputation: 25728

Here you go: http://jsfiddle.net/PCwx8/3/

var seconds = 60-aseconds;
if(parseInt(seconds,10) <10){
    seconds = "0"+seconds;
}

Upvotes: 1

Fortega
Fortega

Reputation: 19682

You could write and use a function like this:

function addZeroIfNeeded(val){
    return val < 10 ? "0" + val : val;   
}

Check http://jsfiddle.net/VafZ7/

Upvotes: 2

Joshua
Joshua

Reputation: 2982

JS will almost definitely parse the "0" as an integer and add zero to i. A bit cumbersome but working is the following:

var i = 0;
if (i < 10) {
    i = "0" + ("" + i);
}
return i;

The trick is, to make sure, that i will become a string. Similar to making an integer a string with numericalStringvar * 1

Upvotes: 0

Antony
Antony

Reputation: 15106

Use ("0" + seconds).slice(-2).

See DEMO.

document.getElementById("seconds").innerHTML= ("0" + seconds).slice(-2);
document.getElementById("hours").innerHTML= ("0" + hours).slice(-2);
document.getElementById("days").innerHTML= ("0" + days).slice(-2);
document.getElementById("minutes").innerHTML= ("0" + minutes).slice(-2);

Upvotes: 1

Related Questions