2017-04-03 114 views
0

因此,从阅读周围我知道我应该将整数(1078美分)表示为美元金额(如$ 10.78)。在javascript货币字符串中转换十进制的最佳方式

My apps input is sometimes pretty ugly. Stuff like "$10.78533999". I know I can use parseFloat + Math.round like so: 

返回Math.round(100 * parseFloat(dollarsAndCentsString.replace(/ [$,] /克, '')));

但我很担心舍入误差。我可以做一些复杂的是这样的:

Number.prototype.round = function(places){ 
    places = Math.pow(10, places); 
    return Math.round((this + Number.EPSILON) * places)/100; 
} 

var shiftDecimal = function(amount){ 
    var amountDecPos = amount.indexOf('.'); 
    var intAmount = amount.substring(0, amount.indexOf('.')); 
    var remainder = parseFloat(amount.substring(amount.indexOf('.') , amount.length)).round(2).toString().substr(2); 
    return intAmount + remainder; 
} 

https://jsfiddle.net/eg0as88b/1/

在那里我有一个自定义的(我认为很准确)取整函数,仅在小数运营商,以尽量减少舍入误差。

这是矫枉过正?它似乎应该有一个更好的方式(特别是性能明智)。谢谢!

+0

你说的是为了显示或存储与计算域的目的?舍入的重要性取决于您的场景。 – Paul

回答

0

最好的方法是使用number.toLocaleString()函数。

这是JavaScript给出的将数字转换为货币的内置函数。

Ex。

var number = 10.78533999; 

console.log(num.toLocaleString(undefined, {maximumFractionDigits: 2})); // Displays "10.79" if in U.S. English locale 

参考链接:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

+0

这似乎工作,当我试图摆脱小数(我不得不使用toFixed(0))时有点麻烦。我是否需要担心如何使用本地字符串?这是一个JSFiddle的整个事情: https://jsfiddle.net/xcrc09L4/3/ –

+0

你不需要担心toLocalString轮。如果我的解决方案为你工作,那么请回答我的答案。 &也是答案。所以其他你知道这个答案是正确的 –

相关问题