【发布时间】:2017-08-28 17:07:23
【问题描述】:
所以通过阅读我知道我应该将美元金额(如 10.78 美元)表示为整数(1078 美分)。
My apps input is sometimes pretty ugly. Stuff like "$10.78533999". I know I can use parseFloat + Math.round like so:
return Math.round(100 * parseFloat(dollarsAndCentsString.replace(/[$,]/g, '')));
但我担心舍入错误。我可以做一些像这样详细的事情:
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/
我有一个自定义(我认为非常准确)的舍入函数,它只对小数部分进行运算符,以最大限度地减少舍入错误。
这是矫枉过正吗?似乎应该有更好的方法(尤其是性能方面)。谢谢!
【问题讨论】:
-
您说的是显示目的还是存储和域计算目的?根据您的情况,舍入的重要性有很大不同。
标签: javascript rounding currency