Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

less than 10 add 0 to number [duplicate]

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

like image 938
uriah Avatar asked Dec 14 '11 23:12

uriah


People also ask

How do you add a leading zero when a number is less than 10?

The safest way is probably to only add zeroes when the length of the column is 1 character: UPDATE Table SET MyCol = '0' + MyCol WHERE LEN(MyCol) = 1; This will cover all numbers under 10 and also ignore any that already have a leading 0.


2 Answers

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.

like image 121
David Hedlund Avatar answered Sep 28 '22 21:09

David Hedlund


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.

like image 38
Guffa Avatar answered Sep 28 '22 22:09

Guffa