Javascript 小于 10 给数字加 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8513032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:19:41  来源:igfitidea点击:

less than 10 add 0 to number

javascriptjquerymath

提问by uriah

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

如何修改此代码以在任何低于 10 的数字之前添加 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);
   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

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

to

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

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

Thanks for your time

谢谢你的时间

回答by dxh

You can always do

你总能做到

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

See slice():

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 Numberwith it:

为了便于访问,您当然可以将其提取为一个函数,甚至可以Number使用它进行扩展:

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 padaccepts an argument specifying the length of the desired string. If no such argument is used, it defaults to 2. You could write:

上面的函数pad接受一个参数,指定所需字符串的长度。如果没有使用这样的参数,它默认为 2。你可以写:

deg.pad(4) // "0045"

Note the obvious drawback that the value of ncannot 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 answerfor an excellent approach to that).

请注意一个明显的缺点,即 的值n不能大于 11,因为 0 的字符串目前只有 10 个字符长。这当然可以给出技术解决方案,但我不想在如此简单的函数中引入复杂性。(如果您选择这样做,请参阅亚历克斯的回答以了解解决此问题的绝佳方法)。

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.

另请注意,您将无法编写2.pad(). 它只适用于变量。但是,如果它不是变量,您将始终事先知道该数字包含多少位数字。

回答by Guffa

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.

等等。

回答by GigolNet Guigolachvili

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

or:

或者:

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

回答by Luis Orantes

You can always do

你总能做到

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

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

如果经常使用,可以扩展对象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.

您可以在其中设置任何焊盘尺寸或保留默认值 2。

回答by alex

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.

js小提琴

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

这样,处理任何任意宽度都不是问题。

回答by buley

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.

我很无聊,正在玩 JSPerf 试图击败当前选择的答案,无论什么和使用slice(-2). 这是一个聪明的方法,但随着字符串变长,性能会变得更糟。

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 charAtso it doesn't have to traverse the whole string.

对于数字 0 到 10(一个和两个字符串),我能够击败大约 10%,并且在通过使用处理更长的字符串时,最快的方法要好得多,charAt因此它不必遍历整个字符串。

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

这个跟随并不像退出那么简单,slice(-2)但是当在大多数 3 位数字(3 个字符串)中使用时,速度要快 86%-89%

var prepended = ( 1 === string.length && string.charAt( 0 ) !== "0" ) ? '0' + string : string;

回答by Berezh

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

回答by Rizwan Shekh

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

这是 Genaric 函数,用于添加任意数量的前导零以生成任意大小的数字字符串。

function add_zero(your_number, length) {
    var num = '' + your_number;
    while (num.length < length) {
        num = '0' + num;
    }
    return num;
}

回答by Mike Samuel

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.

显示预期的输出。

回答by Krzysztof Trzos

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