我正在寻找一个与C/PHP printf()或C#/Java程序员String.Format()(IFormatProvider for.NET)相当的JavaScript。
目前,我的基本要求是数字的千位分隔符格式,但处理大量组合(包括日期)的格式会很好。
我意识到Microsoft的Ajax库提供了String.Format()的一个版本,但我们不希望该框架的全部开销。
我正在寻找一个与C/PHP printf()或C#/Java程序员String.Format()(IFormatProvider for.NET)相当的JavaScript。
目前,我的基本要求是数字的千位分隔符格式,但处理大量组合(包括日期)的格式会很好。
我意识到Microsoft的Ajax库提供了String.Format()的一个版本,但我们不希望该框架的全部开销。
当前回答
我这里有一个稍长的JavaScript格式化程序。。。
可以通过多种方式设置格式:
String.format(输入,args0,arg1,…)String.format(输入,obj)“literal”.格式(arg0,arg1,…)“literal”.format(obj)
此外,如果您使用ObjectBase.prototype.format(例如使用DateJS),它将使用它。
示例。。。
var input = "numbered args ({0}-{1}-{2}-{3})";
console.log(String.format(input, "first", 2, new Date()));
//Outputs "numbered args (first-2-Thu May 31 2012...Time)-{3})"
console.log(input.format("first", 2, new Date()));
//Outputs "numbered args(first-2-Thu May 31 2012...Time)-{3})"
console.log(input.format(
"object properties ({first}-{second}-{third:yyyy-MM-dd}-{fourth})"
,{
'first':'first'
,'second':2
,'third':new Date() //assumes Date.prototype.format method
}
));
//Outputs "object properties (first-2-2012-05-31-{3})"
我还使用了.asFormat作为别名,并进行了一些检测,以防已经存在字符串格式(例如使用MS Ajax Toolkit(我讨厌那个库))。
其他回答
非常优雅:
String.prototype.format = function (){
var args = arguments;
return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (curlyBrack, index) {
return ((curlyBrack == "{{") ? "{" : ((curlyBrack == "}}") ? "}" : args[index]));
});
};
// Usage:
"{0}{1}".format("{1}", "{0}")
信贷转到(断开链接)https://gist.github.com/0i0/1519811
我将添加我自己的发现,这些发现是我问过之后发现的:
number_format(用于千位分隔符/货币格式)sprintf(作者同上)
遗憾的是,sprintf似乎不能像.NET的字符串格式那样处理千位分隔符格式。
如果您希望处理千位分隔符,那么应该真正使用JavaScript Number类中的toLocaleString(),因为它将为用户所在区域设置字符串格式。
JavaScript Date类可以格式化本地化的日期和时间。
有了sprintf.js,你可以制作一个漂亮的小格式
String.prototype.format = function(){
var _args = arguments
Array.prototype.unshift.apply(_args,[this])
return sprintf.apply(undefined,_args)
}
// this gives you:
"{%1$s}{%2$s}".format("1", "0")
// {1}{0}
JavaScript中的数字格式
我来到这个问题页面,希望找到如何在JavaScript中格式化数字,而不引入另一个库。以下是我的发现:
舍入浮点数
JavaScript中sprintf(“%.2f”,num)的等价物似乎是num.toFixed(2),它将num格式化为2位小数,并带舍入(但请参见@ars265下面关于Math.round的评论)。
(12.345).toFixed(2); // returns "12.35" (rounding!)
(12.3).toFixed(2); // returns "12.30" (zero padding)
指数形式
sprintf(“%.2e”,num)的等效值为num.toExponential(2)。
(33333).toExponential(2); // "3.33e+4"
十六进制和其他基数
要以基数B打印数字,请尝试num.toString(B)。JavaScript支持从基数2到36的自动转换(此外,某些浏览器对base64编码的支持有限)。
(3735928559).toString(16); // to base 16: "deadbeef"
parseInt("deadbeef", 16); // from base 16: 3735928559
参考页
JS数字格式快速教程
toFixed()的Mozilla参考页(带有指向Precision()、toExponential()、toLocaleString()等的链接)