在javascript中转换为2钱格式

convert to 2 money format in javascript

本文关键字:2钱 格式 转换 javascript      更新时间:2023-09-26

怎么变成钱串?1200应该是1200

 function setdefaults() {
    document.getElementById('perpetual').checked = true
    document.getElementById('users').value = '1'; 
    math_perpetual = parseInt(document.getElementById('users').value) *   1200; 
    document.getElementById('result').innerHTML = "The total price is $" + math_perpetual;
}

我认为使用一个可以为您处理它的库会更容易。我使用currencyFormatter.js -给它一个尝试。适用于所有浏览器,非常轻量级。它还会为您添加货币符号,并可以根据指定的区域设置格式:

OSREC.CurrencyFormatter.format(2534234, { currency: 'INR' }); // Returns ₹ 25,34,234.00
OSREC.CurrencyFormatter.format(2534234, { currency: 'EUR' }); // Returns 2.534.234,00 €
OSREC.CurrencyFormatter.format(2534234, { currency: 'EUR', locale: 'fr' }); // Returns 2 534 234,00 €

currencyFormatter.js on github

看一下number类中的tolocalstring函数:

MDN页面示例:

var number = 123456.789;
// request a currency format
alert(number.toLocaleString("de-DE", {style: "currency", currency: "EUR"}));
// → 123.456,79 €
// the Japanese yen doesn't use a minor unit
alert(number.toLocaleString("ja-JP", {style: "currency", currency: "JPY"}))
// → ¥123,457
// limit to three significant digits
alert(number.toLocaleString("en-IN", {maximumSignificantDigits: 3}));
// → 1,23,000 * doesn't work for chrome

下面的代码将把你的钱格式化为美元:

function formatDollar(num) {
    var p = num.toFixed(2).split(".");
    return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
        return  num + (i && !(i % 3) ? "," : "") + acc;
    }, "") + "." + p[1];
}
function addThousandsSeparators(n) {
  return (''+n).split('').reverse().join('')
      .match(/('d{1,3})/g).join(',').split('')
      .reverse().join('');
}
addThousandsSeparators(123);        // =>           "123"
addThousandsSeparators(1234);       // =>         "1,234"
addThousandsSeparators(12345);      // =>        "12,345"
addThousandsSeparators(123456);     // =>       "123,456"
addThousandsSeparators(1234567);    // =>     "1,234,567"
addThousandsSeparators(12345678);   // =>    "12,345,678"
addThousandsSeparators(123456789);  // =>   "123,456,789"
addThousandsSeparators(1234567890); // => "1,234,567,890"

您可以使用Intl.NumberFormat。下面是一个例子:

const number = 123456.789;
console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// expected output: "123.456,79 €"
// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// expected output: "¥123,457"
// limit to three significant digits
console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number));
// expected output: "1,23,000"
演示