142

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

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
uriah
  • 2,485
  • 5
  • 28
  • 40
  • Dup: [How can I create a Zerofilled value using JavaScript?](http://stackoverflow.com/q/1267283/90527), [JavaScript, Regex, add leading zero to ALL number contained in string](http://stackoverflow.com/q/9812610/90527), and many others. – outis Mar 29 '12 at 03:08

10 Answers10

354

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.

Community
  • 1
  • 1
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
69

Make a function that you can reuse:

function minTwoDigits(n) {
  return (n < 10 ? '0' : '') + n;
}

Then use it in each part of the coordinates:

c += minTwoDigits(deg) + "° ";

and so on.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 3
    +1. seriously, if you're just dealing with two digits, this is the way to do it; short, simple, effective, easy to read. If you need to think about zero-filling longer numbers, then use one of the other solutions, but if you're just doing two-digit numbers, then this is all you need. – Spudley May 20 '12 at 19:15
  • 1
    This is also about 30% faster than @editor's solution. I benched this solution first, then realised Guffa was already there. – Phil H May 21 '12 at 13:30
  • 1
    This is def the top answer. saved me a ton – kjohnsonthecoder Apr 11 '20 at 02:17
13
if(myNumber.toString().length < 2)
   myNumber= "0"+myNumber;

or:

return (myNumber.toString().length < 2) ? "0"+myNumber : myNumber;
Gigoland
  • 1,287
  • 13
  • 10
12

You can always do

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

If you use it very often, you may extend the object Number

Number.prototype.pad = function(n) {
    if (n==undefined)
        n = 2;

    return (new Array(n).join('0') + this).slice(-n);
}

deg.pad(4) // "0045"

where you can set any pad size or leave the default 2.

Luis Orantes
  • 407
  • 5
  • 13
10

You can write a generic function to do this...

var numberFormat = function(number, width) {
    return new Array(+width + 1 - (number + '').length).join('0') + number;
}

jsFiddle.

That way, it's not a problem to deal with any arbitrarily width.

alex
  • 479,566
  • 201
  • 878
  • 984
3

Here is Genaric function for add any number of leading zeros for making any size of numeric string.

function add_zero(your_number, length) {
    var num = '' + your_number;
    while (num.length < length) {
        num = '0' + num;
    }
    return num;
}
Jayesh Thanki
  • 2,037
  • 2
  • 23
  • 32
2

Hope, this help:

Number.prototype.zeroFill= function (n) {
    var isNegative = this < 0;
    var number = isNegative ? -1 * this : this;
    for (var i = number.toString().length; i < n; i++) {
        number = '0' + number;
    }
    return (isNegative ? '-' : '') + number;
}
Berezh
  • 942
  • 9
  • 12
  • +1 for a thorough, comprehensive zero-fill function (but why not just call it `.zeroFill()`?), though to be honest, I think it's probably overkill for the two-digit numbers in the question. – Spudley May 20 '12 at 19:18
  • :-) think globally. Who knows, maybe it will be helpful in the future for other tasks! – Berezh May 21 '12 at 00:05
  • indeed, that's why the +1. but also thinking pragmatically to the solve the task at hand with minimum effort too. – Spudley May 21 '12 at 18:30
1

I was bored and playing around JSPerf trying to beat the currently selected answer prepending a zero no matter what and using slice(-2). It's a clever approach but the performance gets a lot worse as the string gets longer.

For numbers zero to ten (one and two character strings) I was able to beat by about ten percent, and the fastest approach was much better when dealing with longer strings by using charAt so it doesn't have to traverse the whole string.

This follow is not quit as simple as slice(-2) but is 86%-89% faster when used across mostly 3 digit numbers (3 character strings).

var prepended = ( 1 === string.length && string.charAt( 0 ) !== "0" ) ? '0' + string : string;
buley
  • 28,032
  • 17
  • 85
  • 106
  • As it goes, @Guffa's solution is about 30% faster than this on with charAt in. By using a numeric check and a ternary operator, there's only 1 string cast and no char interrogation. – Phil H May 21 '12 at 13:31
0

A single regular expression replace should do it:

var stringWithSmallIntegers = "4° 7′ 34″W, 168° 1′ 23″N";

var paddedString = stringWithSmallIntegers.replace(
    /\d+/g,
    function pad(digits) {
        return digits.length === 1 ? '0' + digits : digits;
    });

alert(paddedString);

shows the expected output.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
0
$('#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);
   if(deg < 10) deg = '0' + deg;
   c += deg + "° ";

   r = (r - deg) * 60;
   var min = Math.floor(r);
   if(min < 10) min = '0' + min;
   c += min + "′ ";

   r = (r - min) * 60;
   var sec = Math.floor(r);
   if(sec < 10) sec = '0' + sec;
   c += sec + "″";

   return c;
}
Jazi
  • 6,569
  • 13
  • 60
  • 92