I am working on a calculator app which works perfectly but starts giving wrong calculations if the output is bigger than 15 digit number. The following is an example code
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));
}
}
});
Now if i put "9999999999999999" in edittext1 and "1" in edittext2, the textview1(result TextView) shows "10000000000000000". The difference is even bigger for a bigger number.
How to fix this?
This is one of my very first questions, so sorry if it doesn't make any sense or is a stupid question!
We use BigDecimal
for high-precision arithmetic. We also use it for calculations
requiring control over scale and rounding off behavior
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
you can use this