[javascript] less than 10 add 0 to number

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

This question is related to javascript jquery math

The answer is


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;
}

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;

$('#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;
}

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.


if(myNumber.toString().length < 2)
   myNumber= "0"+myNumber;

or:

return (myNumber.toString().length < 2) ? "0"+myNumber : myNumber;

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.


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.


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;
}

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to math

How to do perspective fixing? How to pad a string with leading zeros in Python 3 How can I use "e" (Euler's number) and power operation in python 2.7 numpy max vs amax vs maximum Efficiently getting all divisors of a given number Using atan2 to find angle between two vectors How to calculate percentage when old value is ZERO Finding square root without using sqrt function? Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt? How do I get the total number of unique pairs of a set in the database?