Javascript 中的 String.Format?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6220693/
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
String.Format in Javascript?
提问by Mohammad Dayyan
In C# whenever I wanted to print two digit numbers I've used
在 C# 中,每当我想打印我使用过的两位数时
int digit=1;
Console.Write(digit.ToString("00"));
How can I do the same action in Javascript ?
Thanks
如何在 Javascript 中执行相同的操作?
谢谢
回答by KooiInc
c# digit.toString("00")
appends one zero to the left of digit
(left padding). In javascript I use this functon for that:
c#digit.toString("00")
在digit
(左填充)的左边追加一个零。在 javascript 中,我为此使用了这个函数:
function zeroPad(nr,base){
var len = (String(base).length - String(nr).length)+1;
return len > 0? new Array(len).join('0')+nr : nr;
}
zeroPad(1,10); //=> 01
zeroPad(1,100); //=> 001
zeroPad(1,1000); //=> 0001
You can also rewrite it as an extention to Number:
您还可以将其重写为 Number 的扩展:
Number.prototype.zeroPad = Number.prototype.zeroPad ||
function(base){
var nr = this, len = (String(base).length - String(nr).length)+1;
return len > 0? new Array(len).join('0')+nr : nr;
};
//usage:
(1).zeroPad(10); //=> 01
(1).zeroPad(100); //=> 001
(1).zeroPad(1000); //=> 0001
回答by Hubro
One way would be to download sprintf for javascriptand writing something like this:
一种方法是为 javascript下载sprintf并编写如下内容:
int i = 1;
string s = sprintf("%02d", i);
document.write(s); // Prints "01"
回答by DavidMc
I usually just do something like
("00000000"+nr).slice(-base)
where nr
is the number and base
is the number of digits you want to end up with.
我通常只是做一些事情,比如数字
("00000000"+nr).slice(-base)
在哪里nr
,以及base
你想要得到的位数。
回答by Anubhav Ranjan
var num =10
document.write(num);
But if your question is to use two digit numbers twice then you can use this
但是如果你的问题是两次使用两位数,那么你可以使用这个
var num1 = 10;
var num2 = 20;
var resultStr = string.concat(num1,num2);
document.write(resultStr);
...
Result: 1020
if you want a space in between,
如果你想中间有一个空间,
var resultStr = string.concat(num1,"",num2);
Hope this helps...
希望这可以帮助...