var num = 5;
alert( num.toFixed(1) ); // Show one extra zero after our number five
alert( num.toFixed(2) ); // Pad with one or two zeros after the period
function get2D( num ) {
if( num.toString().length < 2 ) // Integer of less than two digits
return "0" + num; // Prepend a zero!
return num.toString(); // return string for consistency
}
alert( get2D( 3 ) ); // returns '03'
alert( get2D( 19 ) ); // returns '19'
Note: in line 3 above, we don't need to call toString() because JavaScript automatically converts anything to a string when you use the concatenation operator ("+") with a string.
function get2D( num ) {
return ( num.toString().length < 2 ? "0"+num : num ).toString();
}
Caution: in both cases covered in this tutorial, you get a string back, no longer a number!