问题描述
我正在开发一个计算器应用程序,它运行良好,但如果输出大于 15 位数字,则开始给出错误的计算。 以下是示例代码
private double result = 0;
edittext1 = (EditText) findViewById(R.id.edittext1);
edittext2 = (EditText) findViewById(R.id.edittext2);
button1 = (Button) findViewById(R.id.button1)
textview1 = (TextView) findViewById(R.id.textview1);
ArrayList<String> nums = new ArrayList<>();
ArrayList<String> signs = new ArrayList<>();
button1.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View _view) {
//This part is essential (adding strings to arraylists)
nums.add(edittext1.getText().toString());
nums.add(edittext2.getText().toString());
signs.add("*");
if (signs.contains("*")) {
result = Double.parseDouble(nums.get((int)(0))) * Double.parseDouble(nums.get((int)(1)));
//error here (perhaps)
textview1.setText(new DecimalFormat(#.##).format(result));
}
}
});
现在,如果我将“9999999999999999”放入edittext1,将“1”放入edittext2,则textview1(结果TextView)显示“10000000000000000”。 数字越大,差异就越大。
如何解决这个问题?
这是我的第一个问题之一,如果它没有任何意义或者是一个愚蠢的问题,那么抱歉!
解决方法
我们使用 BigDecimal
进行高精度算术。我们还将它用于需要控制规模和四舍五入行为的 calculations
double number1 = 0.05;
double number2 = 0.06;
double result = b - a;
result = 0.009999999999999998
BigDecimal number1 = new BigDecimal("0.05");
BigDecimal number2 = new BigDecimal("0.06");
BigDecimal result = number2.subtract(number1);
result = 0.01
你可以使用this