我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
当前回答
看看JavaScriptNumber对象,看看它是否可以帮助您。
toLocaleString()将使用位置特定的千位分隔符格式化数字。toFixed()将数字舍入到特定的小数位数。
要同时使用这些值,必须将其类型改回数字,因为它们都输出字符串。
例子:
Number((someNumber).toFixed(1)).toLocaleString()
EDIT
您可以直接使用toLocaleString,而不必重新转换为数字:
someNumber.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
多个数字
如果需要经常以类似的方式格式化数字,可以创建一个特定的对象以供重用。德语(瑞士):
const money = new Intl.NumberFormat('de-CH',
{ style:'currency', currency: 'CHF' });
const percent = new Intl.NumberFormat('de-CH',
{ style:'percent', maximumFractionDigits: 1, signDisplay: "always"});
其可以用作:
money.format(1234.50); // output CHF 1'234.50
percent.format(0.083); // output +8.3%
非常漂亮。
其他回答
我建议使用Google可视化API中的NumberFormat类。
你可以这样做:
var formatter = new google.visualization.NumberFormat({
prefix: '$',
pattern: '#,###,###.##'
});
formatter.formatValue(1000000); // $ 1,000,000
我想要一个自动返回小数部分的普通JavaScript解决方案。
function formatDollar(amount) {
var dollar = Number(amount).toLocaleString("us", "currency");
// Decimals
var arrAmount = dollar.split(".");
if (arrAmount.length==2) {
var decimal = arrAmount[1];
if (decimal.length==1) {
arrAmount[1] += "0";
}
}
if (arrAmount.length==1) {
arrAmount.push("00");
}
return "$" + arrAmount.join(".");
}
console.log(formatDollar("1812.2");
Patrick热门答案的CoffeeScript:
Number::formatMoney = (decimalPlaces, decimalChar, thousandsChar) ->
n = this
c = decimalPlaces
d = decimalChar
t = thousandsChar
c = (if isNaN(c = Math.abs(c)) then 2 else c)
d = (if d is undefined then "." else d)
t = (if t is undefined then "," else t)
s = (if n < 0 then "-" else "")
i = parseInt(n = Math.abs(+n or 0).toFixed(c)) + ""
j = (if (j = i.length) > 3 then j % 3 else 0)
s + (if j then i.substr(0, j) + t else "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (if c then d + Math.abs(n - i).toFixed(c).slice(2) else "")
JavaScript中没有“formatNumber”的等价物。你可以自己写,也可以找一个已经这样做的库。
只需使用本机javascript Intl
您只需使用选项设置其值的格式
常量编号=1233445.5678console.log(新的Intl.NumberFormat('en-US',{style:'currency',currency:'USD'}).format(数字));
mozilla文档链接