2012-11-09 78 views
0

可能重複:
How can I format numbers as money in JavaScript?數字貨幣格式問題

這是當前代碼我使用:

f[0].update(parseFloat($('tier').getValue().replace('$','').replace(',',''))*parseFloat(text.replace('$','').replace(',',''))); 

我遇到的問題是價格顯示沒有$而不是適當的貨幣。 例如,應該顯示爲$29.50的東西顯示爲29.5或應顯示爲$5.00顯示爲5的內容。

+0

我倒是建議使用Numeral.js,用於格式化和操作的數字圖書館。還支持貨幣。 http://numeraljs.com – joko13

+0

這是爲magento,雖然... – ryanb4614

回答

0

看一看toFixed()方法從accounting.js。這將解決您的舍入誤差&也格式化錢正確

toFixed() - better rounding for floating point numbers 

     /** 
* Implementation of toFixed() that treats floats more like decimals 
* 
* Fixes binary rounding issues (eg. (0.615).toFixed(2) === "0.61") that present 
* problems for accounting- and finance-related software. 
*/ 
var toFixed = lib.toFixed = function(value, precision) { 
precision = checkPrecision(precision, lib.settings.number.precision); 
var power = Math.pow(10, precision); 

// Multiply up by precision, round accurately, then divide and use native toFixed(): 
return (Math.round(lib.unformat(value) * power)/power).toFixed(precision); 
}; 

鏈接:http://josscrowcroft.github.com/accounting.js/#methods

+0

這是爲magento所以我不相信accounting.js會受益我認爲代碼需要改變一點。 – ryanb4614

+0

它不像你不能在magento動力網站上運行JS。無論如何,如果由於某種原因你不能使用完整的庫。你可以把你需要的代碼(在此張貼的代碼片段)用於編寫你自己的功能。將只是4-5線的代碼 – CuriousMind