less than 10 add 0 to number

uriah picture uriah · Dec 15, 2011 · Viewed 136k times · Source

How can I modify this code to add a 0 before any digits lower than 10

$('#detect').html( toGeo(apX, screenX)  + latT +', '+ toGeo(apY, screenY) + lonT  );

function toGeo(d, max) {
   var c = '';

   var r = d/max * 180;
   var deg = Math.floor(r);
   c += deg + "° ";

   r = (r - deg) * 60;
   var min = Math.floor(r);
   c += min + "′ ";

   r = (r - min) * 60;
   var sec = Math.floor(r);
   c += sec + "″";

   return c;
}

So the outpout would change from

4° 7′ 34″W, 168° 1′ 23″N

to

04° 07′ 34″W, 168° 01′ 23″N

Thanks for your time

Answer

David Hedlund picture David Hedlund · Dec 15, 2011

You can always do

('0' + deg).slice(-2)

See slice():

You can also use negative numbers to select from the end of an array

Hence

('0' + 11).slice(-2) // '11'
('0' + 4).slice(-2)  // '04'

For ease of access, you could of course extract it to a function, or even extend Number with it:

Number.prototype.pad = function(n) {
    return new Array(n).join('0').slice((n || 2) * -1) + this;
}

Which will allow you to write:

c += deg.pad() + '° '; // "04° "

The above function pad accepts an argument specifying the length of the desired string. If no such argument is used, it defaults to 2. You could write:

deg.pad(4) // "0045"

Note the obvious drawback that the value of n cannot be higher than 11, as the string of 0's is currently just 10 characters long. This could of course be given a technical solution, but I did not want to introduce complexity in such a simple function. (Should you elect to, see alex's answer for an excellent approach to that).

Note also that you would not be able to write 2.pad(). It only works with variables. But then, if it's not a variable, you'll always know beforehand how many digits the number consists of.