我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
当前回答
许多答案都有有益的想法,但没有一个能满足我的需求。所以我使用了所有的想法,并构建了这个示例:
function Format_Numb(fmt){
var decimals = isNaN(decimals) ? 2 : Math.abs(decimals);
if(typeof decSgn === "undefined") decSgn = ".";
if(typeof kommaSgn === "undefined") kommaSgn= ",";
var s3digits = /(\d{1,3}(?=(\d{3})+(?=[.]|$))|(?:[.]\d*))/g;
var dflt_nk = "00000000".substring(0, decimals);
//--------------------------------
// handler for pattern: "%m"
var _f_money = function(v_in){
var v = v_in.toFixed(decimals);
var add_nk = ",00";
var arr = v.split(".");
return arr[0].toString().replace(s3digits, function ($0) {
return ($0.charAt(0) == ".")
? ((add_nk = ""), (kommaSgn + $0.substring(1)))
: ($0 + decSgn);
})
+ ((decimals > 0)
? (kommaSgn
+ (
(arr.length > 1)
? arr[1]
: dflt_nk
)
)
: ""
);
}
// handler for pattern: "%<len>[.<prec>]f"
var _f_flt = function(v_in, l, prec){
var v = (typeof prec !== "undefined") ? v_in.toFixed(prec) : v_in;
return ((typeof l !== "undefined") && ((l=l-v.length) > 0))
? (Array(l+1).join(" ") + v)
: v;
}
// handler for pattern: "%<len>x"
var _f_hex = function(v_in, l, flUpper){
var v = Math.round(v_in).toString(16);
if(flUpper) v = v.toUpperCase();
return ((typeof l !== "undefined") && ((l=l-v.length) > 0))
? (Array(l+1).join("0") + v)
: v;
}
//...can be extended..., just add the function, for example: var _f_octal = function( v_in,...){
//--------------------------------
if(typeof(fmt) !== "undefined"){
//...can be extended..., just add the char, for example "O": MFX -> MFXO
var rpatt = /(?:%([^%"MFX]*)([MFX]))|(?:"([^"]*)")|("|%%)/gi;
var _qu = "\"";
var _mask_qu = "\\\"";
var str = fmt.toString().replace(rpatt, function($0, $1, $2, $3, $4){
var f;
if(typeof $1 !== "undefined"){
switch($2.toUpperCase()){
case "M": f = "_f_money(v)"; break;
case "F": var n_dig0, n_dig1;
var re_flt =/^(?:(\d))*(?:[.](\d))*$/;
$1.replace(re_flt, function($0, $1, $2){
n_dig0 = $1;
n_dig1 = $2;
});
f = "_f_flt(v, " + n_dig0 + "," + n_dig1 + ")"; break;
case "X": var n_dig = "undefined";
var re_flt = /^(\d*)$/;
$1.replace(re_flt, function($0){
if($0 != "") n_dig = $0;
});
f = "_f_hex(v, " + n_dig + "," + ($2=="X") + ")"; break;
//...can be extended..., for example: case "O":
}
return "\"+"+f+"+\"";
} else if(typeof $3 !== "undefined"){
return _mask_qu + $3 + _mask_qu;
} else {
return ($4 == _qu) ? _mask_qu : $4.charAt(0);
}
});
var cmd = "return function(v){"
+ "if(typeof v === \"undefined\")return \"\";" // null returned as empty string
+ "if(!v.toFixed) return v.toString();" // not numb returned as string
+ "return \"" + str + "\";"
+ "}";
//...can be extended..., just add the function name in the 2 places:
return new Function("_f_money,_f_flt,_f_hex", cmd)(_f_money,_f_flt,_f_hex);
}
}
首先,我需要一个C样式格式的字符串定义,它应该是灵活的,但非常容易使用,我用以下方式定义它:;模式:
%[<len>][.<prec>]f float, example "%f", "%8.2d", "%.3f"
%m money
%[<len>]x hexadecimal lower case, example "%x", "%8x"
%[<len>]X hexadecimal upper case, example "%X", "%8X"
因为对我来说,除了欧元之外,没有任何其他格式的需要,所以我只实现了“%m”。
但这很容易扩展。。。与C中一样,格式字符串是包含模式的字符串。例如,对于欧元:“%m€”(返回类似“8.129,33€”的字符串)
除了灵活性之外,我还需要一个处理表的快速解决方案。这意味着,在处理数千个单元格时,格式字符串的处理不能重复一次。我不接受类似“format(value,fmt)”的调用,但这必须分为两个步骤:
// var formatter = Format_Numb( "%m €");
// simple example for Euro...
// but we use a complex example:
var formatter = Format_Numb("a%%%3mxx \"zz\"%8.2f°\" >0x%8X<");
// formatter is now a function, which can be used more than once (this is an example, that can be tested:)
var v1 = formatter(1897654.8198344);
var v2 = formatter(4.2);
... (and thousands of rows)
同样为了提高性能,_f_money包含正则表达式;
第三,类似“format(value,fmt)”的调用是不可接受的,因为:
虽然可以用不同的掩码格式化不同的对象集合(例如,列的单元格),但我不想在处理时处理格式化字符串。此时,我只想使用格式,如
for(单元格中的var单元格){do_something(cell.col.formatter(cell.value));}
什么格式-可能是在.ini文件中,在XML中为每一列或其他地方定义的。。。,但是分析和设置格式或处理国际化完全是在另一个地方进行的,在那里我想将格式化程序分配给集合,而不考虑性能问题:
col.formatter=格式_字符串(_getFormatForColumn(…));
第四,我想要一个“宽容”的解决方案,因此传递例如字符串而不是数字应该只返回字符串,但“null”应该返回一个空字符串。
(如果值太大,格式化“%4.2f”也不能剪切。)
最后,但并非最不重要的是,它应该是可读的,易于扩展,而不会对性能产生任何影响。。。例如,如果某人需要“八进制值”,请参考带有“…可以扩展…”的行-我认为这应该是一项非常简单的任务。
我的整体重点是表现。每个“处理例程”(例如,_f_money)都可以被封装优化,或者在这个或其他线程中与其他思想进行交换,而无需更改“准备例程”(分析格式字符串和创建函数),这些例程只能被处理一次,从这个意义上说,与数千个数字的转换调用相比,性能并不那么关键。
对于所有喜欢数字方法的人来说:
Number.prototype.format_euro = (function(formatter){
return function(){ return formatter(this); }})
(Format_Numb( "%m €"));
var v_euro = (8192.3282).format_euro(); // results: 8.192,33 €
Number.prototype.format_hex = (function(formatter){
return function(){ return formatter(this); }})
(Format_Numb( "%4x"));
var v_hex = (4.3282).format_hex();
虽然我测试了一些,但代码中可能有很多错误。因此,它不是一个现成的模块,只是像我这样的非JavaScript专家的一个想法和起点。
该代码包含了许多StackOverflow帖子中修改过的想法;很抱歉,我不能引用所有这些,但感谢所有的专家。
其他回答
toLocaleString很好,但它不适用于所有浏览器。我通常使用currencyFormatter.js(https://osrec.github.io/currencyFormatter.js/). 它非常轻量级,包含所有现成的货币和语言环境定义。它还擅长格式化格式异常的货币,如INR(以10万卢比、10万卢比等为单位分组)。此外,没有任何依赖关系!
OSREC.CurrencyFormatter.format(2534234,{currency:'INR'});//退换商品₹ 25,34,234.00
OSREC.CurrencyFormatter.format(2534234,{currency:'EUR'});//退货2.534.234,00欧元
OSREC.CurrencyFormatter.format(2534234,{currency:'EUR',locale:'fr'});//退货2 534 234,00欧元
我想你想要:
f.nettotal.value = "$" + showValue.toFixed(2);
使用正则表达式的较短方法(用于插入空格、逗号或点):
Number.prototype.toCurrencyString = function(){
return this.toFixed(2).replace(/(\d)(?=(\d{3})+\b)/g, '$1 ');
}
n = 12345678.9;
alert(n.toCurrencyString());
这是另一个尝试,只是为了好玩:
function formatDollar(num) {
var p = num.toFixed(2).split(".");
return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
return num + (num != "-" && i && !(i % 3) ? "," : "") + acc;
}, "") + "." + p[1];
}
还有一些测试:
formatDollar(45664544.23423) // "$45,664,544.23"
formatDollar(45) // "$45.00"
formatDollar(123) // "$123.00"
formatDollar(7824) // "$7,824.00"
formatDollar(1) // "$1.00"
formatDollar(-1345) // "$-1,345.00
formatDollar(-3) // "$-3.00"
下面是Patrick Desjardins(别名Daok)代码,添加了一些注释和一些小改动:
/*
decimal_sep: character used as decimal separator, it defaults to '.' when omitted
thousands_sep: char used as thousands separator, it defaults to ',' when omitted
*/
Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep)
{
var n = this,
c = isNaN(decimals) ? 2 : Math.abs(decimals), // If decimal is zero we must take it. It means the user does not want to show any decimal
d = decimal_sep || '.', // If no decimal separator is passed, we use the dot as default decimal separator (we MUST use a decimal separator)
/*
According to [https://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]
the fastest way to check for not defined parameter is to use typeof value === 'undefined'
rather than doing value === undefined.
*/
t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, // If you don't want to use a thousands separator you can pass empty string as thousands_sep value
sign = (n < 0) ? '-' : '',
// Extracting the absolute value of the integer part of the number and converting to string
i = parseInt(n = Math.abs(n).toFixed(c)) + '',
j = ((j = i.length) > 3) ? j % 3 : 0;
return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
}
这里有一些测试:
// Some tests (do not forget parenthesis when using negative numbers and number with no decimals)
alert(123456789.67392.toMoney() + '\n' + 123456789.67392.toMoney(3) + '\n' + 123456789.67392.toMoney(0) + '\n' + (123456).toMoney() + '\n' + (123456).toMoney(0) + '\n' + 89.67392.toMoney() + '\n' + (89).toMoney());
// Some tests (do not forget parenthesis when using negative numbers and number with no decimals)
alert((-123456789.67392).toMoney() + '\n' + (-123456789.67392).toMoney(-3));
次要变化包括:
移动了一点Math.abs(小数),只有当不是NaN时才能执行。decimal_sep不能再是空字符串(必须使用某种十进制分隔符)我们使用typeof thousand_sep===“undefined”,如How best to determine if a argument is not send to JavaScript function中所建议的不需要(+n||0),因为这是Number对象
JSFiddle公司