2014-07-01 32 views
0

我該如何變成錢串? 1200應該是1200在javascript中轉換爲2種貨幣格式

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; 
} 
+0

http://stackoverflow.com/questions/3753483/javascript-thousand-separator-string -format – Mate

+0

似乎是http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript的重複。看看它。 – Mritunjay

回答

1

拿在number類看看toLocaleString功能:

例如,從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 
0

下面的代碼將在美元格式化你的錢:

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]; 
} 
0
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" 
1

我認爲使用一個能夠爲您處理它的庫會更容易。我使用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