格式化为货币的 Javascript 函数

标签 javascript

我有一个脚本,我向它传递一个字符串,它会返回格式化为美元的字符串。因此,如果我发送“10000”,它将返回“$10,000.00”。 现在的问题是,当我发送“1000000”(100 万美元)时,它会返回“$1,000.00”,因为它只是设置为基于一组零进行解析。这是我的脚本,如何调整它以考虑两组零(100 万美元)?

String.prototype.formatMoney = function(places, symbol, thousand, decimal) {
if((this).match(/^\$/) && (this).indexOf(',') != -1 && (this).indexOf('.') != -1) {
    return this;
}
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    symbol = symbol !== undefined ? symbol : "$";
    thousand = thousand || ",";
    decimal = decimal || ".";
var number = Number(((this).replace('$','')).replace(',','')), 
    negative = number < 0 ? "-" : "",
    i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
    j = (j = i.length) > 3 ? j % 3 : 0;
return negative + symbol + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : ""); };

预先感谢您提供任何有用的信息!

最佳答案

function formatMoney(number) {
  return number.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
}

console.log(formatMoney(10000));   // $10,000.00
console.log(formatMoney(1000000)); // $1,000,000.00

关于格式化为货币的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40426965/

相关文章:

javascript - 在 JS Web Scraping Cheerio 中获得结果是不可能的

javascript - 使用对象解构语法设置先前初始化的变量的值

javascript - 使用js创建一个带有单选框的弹出窗口

javascript - 右键单击特定图例项

javascript - 为什么我们需要返回一个流而不是直接调度一个值?

javascript - 如何在 HTMLCollection 上通过类名获取元素

javascript - 使用 jQuery、laravel 5.3 在提交时将表单数据发送到 div,在表单外

javascript - 调查 Monkey API 事件

javascript - 如何重复div类?

javascript - 通过 JavaScript 重新加载页面并重新发送表单信息