我目前正在使用BigDecimal
,这是我获取2个精度数字的实现之一:
mDbHelper.open();
BigDecimal total = mDbHelper
.getTotal(Type.Income, "20130101 12:00:00", "20131231 12:00:00");
BigDecimal expense = mDbHelper.getTotal(Type.Expense, "20130101 12:00:00",
"20131231 12:00:00");
BigDecimal saving = mDbHelper.getSaving("feb");
mDbHelper.close();
BigDecimal remaining = total.subtract(expense.add(saving));
Log.d("total get", total.toPlainString());
Log.d("expense get", expense.toPlainString());
Log.d("saving get", saving.toPlainString());
Log.d("remaining get", remaining.toPlainString());
try {
percentRemain = (double) Math.round(remaining.multiply(new BigDecimal(10000.0))
.divide(total, BigDecimal.ROUND_HALF_UP).doubleValue()) / 100;
Log.d("percentRemain", "" + percentRemain);
percentExpense = (double) Math.round(expense.multiply(new BigDecimal(10000.0))
.divide(total, BigDecimal.ROUND_HALF_UP).doubleValue()) / 100;
Log.d("percentExpense", "" + percentExpense);
Log.d("before calculation saving =", saving.toPlainString());
Log.d("before calculation total =", total.toPlainString());
percentSaving = ((double) Math.round(saving.multiply(new BigDecimal(10000.0))
.divide(total, BigDecimal.ROUND_HALF_UP).doubleValue())) / 100d;
Log.d("percentSaving", "" + percentSaving);
Log.d("multiply", "" + saving.multiply(new BigDecimal(10000.0)).doubleValue());
Log.d("divide",
""
+ saving.multiply(new BigDecimal(10000.0))
.divide(total, BigDecimal.ROUND_HALF_UP).doubleValue());
} catch (ArithmeticException e) {
e.printStackTrace();
percentRemain = 0.0f;
percentExpense = 0.0f;
percentSaving = 0.0f;
}
percentSaving == 0.0
saving >= 10,000,000
任何观点?请指导我。
这是我记录的变量值:
02-28 16:55:12.250: D/total get(29448): 41623000
02-28 16:55:12.250: D/expense get(29448): 7186545.0
02-28 16:55:12.250: D/saving get(29448): 10000000
02-28 16:55:12.250: D/remaining get(29448): 24436455.0
02-28 16:55:12.250: D/percentRemain(29448): 58.71
02-28 16:55:12.250: D/percentExpense(29448): 17.27
02-28 16:55:12.250: D/before calculation saving =(29448): 10000000
02-28 16:55:12.250: D/before calculation total =(29448): 41623000
02-28 16:55:12.250: D/percentSaving(29448): 0.0
02-28 16:55:12.250: D/multiply(29448): 1.0E11
02-28 16:55:12.250: D/divide(29448): 0.0
percentExpense
与percentSaving
添加了我的方法和日志。抱歉这个烂摊子。
解决方案
我已将公式更改为此,现在看起来它返回了正确的值。
percentExpense = (double) Math.round(expense.multiply(new BigDecimal(10000.0))
.divide(total, 4, BigDecimal.ROUND_HALF_UP).doubleValue()) / 100;