因此,从阅读周围我知道我应该将整数(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/
在那里我有一个自定义的(我认为很准确)取整函数,仅在小数运营商,以尽量减少舍入误差。
这是矫枉过正?它似乎应该有一个更好的方式(特别是性能明智)。谢谢!
你说的是为了显示或存储与计算域的目的?舍入的重要性取决于您的场景。 – Paul