小于10加0到数字 [英] less than 10 add 0 to number
问题描述
如何修改此代码,以便在任何低于10的数字之前添加0
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;
}
所以输出将从
4°7'34W,168°1'23N
4° 7′ 34″W, 168° 1′ 23″N
到
04°07'34W,168°01'23N
04° 07′ 34″W, 168° 01′ 23″N
感谢您的时间
推荐答案
你可以随时
('0' + deg).slice(-2)
参见 slice()
:
您也可以使用负数从数组的末尾进行选择
You can also use negative numbers to select from the end of an array
因此
('0' + 11).slice(-2) // '11'
('0' + 4).slice(-2) // '04'
为了便于访问,您当然可以将其提取到函数中,甚至可以扩展 Number
with it:
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;
}
这将允许你写:
c += deg.pad() + '° '; // "04° "
以上函数 pad
接受指定所需字符串长度的参数。如果没有使用这样的参数,它默认为2.您可以写:
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"
注意 n $ c $的值的明显缺点c>不能高于11,因为0的字符串当前只有10个字符长。这当然可以给出技术解决方案,但我不想在这样一个简单的功能中引入复杂性。 (如果您选择,请参阅 alex的回答以获得优秀的解决方案)。
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).
另请注意,您将无法编写 2.pad()
。它只适用于变量。但是,如果它不是变量,您将始终事先知道该数字包含多少位数。
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.
这篇关于小于10加0到数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!