如何将数字格式化为货币字符串? [英] How to format numbers as currency string?
问题描述
我想用JavaScript格式化价格。我想要一个函数,该函数以 float
作为参数,并返回格式如下的 string
:
I would like to format a price in JavaScript. I'd like a function which takes a float
as an argument and returns a string
formatted like this:
"$ 2,500.00"
执行此操作的最佳方法是什么?
What's the best way to do this?
推荐答案
Number.prototype.toFixed
该解决方案与每个主流浏览器都兼容:
Number.prototype.toFixed
This solution is compatible with every single major browser:
const profits = 2489.8237;
profits.toFixed(3) //returns 2489.824 (rounds up)
profits.toFixed(2) //returns 2489.82
profits.toFixed(7) //returns 2489.8237000 (pads the decimals)
所有您需要添加的货币符号(例如 $ + Profits.toFixed(2)
),您将获得美元金额。
All you need is to add the currency symbol (e.g. "$" + profits.toFixed(2)
) and you will have your amount in dollars.
如果需要在每个数字之间使用 ,则可以使用以下功能:
If you require the use of ,
between each digit, you can use this function:
function formatMoney(number, decPlaces, decSep, thouSep) {
decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
decSep = typeof decSep === "undefined" ? "." : decSep;
thouSep = typeof thouSep === "undefined" ? "," : thouSep;
var sign = number < 0 ? "-" : "";
var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces)));
var j = (j = i.length) > 3 ? j % 3 : 0;
return sign +
(j ? i.substr(0, j) + thouSep : "") +
i.substr(j).replace(/(\decSep{3})(?=\decSep)/g, "$1" + thouSep) +
(decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : "");
}
document.getElementById("b").addEventListener("click", event => {
document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value);
});
<label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label>
<br />
<button id="b">Get Output</button>
<p id="x">(press button to get output)</p>
使用像这样:
(123456789.12345).formatMoney(2, ".", ",");
如果您始终要使用'。'和',',则可以不使用它们
If you're always going to use '.' and ',', you can leave them off your method call, and the method will default them for you.
(123456789.12345).formatMoney(2);
如果您的文化中两个符号都翻转了(即欧洲人),并且您想使用默认值,只需在 formatMoney
方法中粘贴以下两行即可:
If your culture has the two symbols flipped (i.e. Europeans) and you would like to use the defaults, just paste over the following two lines in the formatMoney
method:
d = d == undefined ? "," : d,
t = t == undefined ? "." : t,
自定义功能(ES6)
如果您可以使用现代ECMAScript语法(即通过Babel),则可以改用以下更简单的函数:
Custom function (ES6)
If you can use modern ECMAScript syntax (i.e. through Babel), you can use this simpler function instead:
function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") {
try {
decimalCount = Math.abs(decimalCount);
decimalCount = isNaN(decimalCount) ? 2 : decimalCount;
const negativeSign = amount < 0 ? "-" : "";
let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();
let j = (i.length > 3) ? i.length % 3 : 0;
return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");
} catch (e) {
console.log(e)
}
};
document.getElementById("b").addEventListener("click", event => {
document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value);
});
<label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label>
<br />
<button id="b">Get Output</button>
<p id="x">(press button to get output)</p>
这篇关于如何将数字格式化为货币字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!