为了赚钱,您应该在Java中使用哪种舍入方法? [英] What rounding method should you use in Java for money?
问题描述
假设我在Java中有一个十进制值表示货币。
Suppose I have a decimal value in Java that represents money.
四舍五入这些值的最佳方法是什么?
What's the best way to round these values?
例如,如果我有一个基于税率计算的值,而最后得到的结果是税额 5.3999999999999995
,我将其四舍五入到小数点后两位:
For example, if I have a value that's calculated based on a tax rate and I end up with a result of, say, 5.3999999999999995
as the tax amount, should I round it to 2 decimal places simply by doing this:
double d = 5.3999999999999995
BigDecimal bd = new BigDecimal(d).setScale(2, RoundingMode.HALF_EVEN);
d = bd.doubleValue();
产生货币值:
5.40
推荐答案
最多计算货币的应用程序不使用浮点数( double
, float
);他们使用代表较小单位的整数。例如,在$ USD中,货币可以用 pennies 表示,即1美元的1/100。
Most applications that calculate money don't use floating point (double
, float
); they use integer amounts representing a smaller unit. For example in $USD, money can be represented in pennies which is 1/100 of a dollar.
为获得更好的准确性,您可能希望使用代表1E-03(毫安美元)或1E-06的整数。这取决于诸如利息计算和您的精确度等问题。
For better accuracy, you may want to have an integer represent 1E-03 ("milli-dollars") or 1E-06. This depends on issues such as interest calculations and your level of precision.
这篇关于为了赚钱,您应该在Java中使用哪种舍入方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!