2012-11-09 75 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