amirmamed
amirmamed

Reputation: 41

BigDecimal doesn't calculate divide

I divided 124/13. but the app forced close. this is my code:

Float x =Float.valueOf(a.getText().toString());
Float y =Float.valueOf(b.getText().toString());
BigDecimal xx= new BigDecimal (x);
BigDecimal yy= new BigDecimal (y);
BigDecimal rx= xx.divide(yy);
res.setText("=" + rx);

Upvotes: 1

Views: 161

Answers (2)

rzymek
rzymek

Reputation: 9281

You have encountered:

java.lang.ArithmeticException: Non-terminating decimal expansion; 
    no exact representable decimal result.

Consider this example, which will yeld this exact exception:

BigDecimal x = new BigDecimal(1);
BigDecimal y = new BigDecimal(3);
BigDecimal result = x.divide(y);

That's because there's no exact representation of 0.3333(3). What you need to do is to specify rounding and precision:

BigDecimal result = x.divide(y, 10 /*scale*/, RoundingMode.HALF_UP);
System.out.println(result); //will print "0.3333333333"

Also note that you should create the BigDecimal directly from String, as float is not a precise representation. Consider this:

String s = "0.123456789";
System.out.println(Float.parseFloat(s)); //prints 0.12345679
System.out.println(new BigDecimal(s));   //prints 0.123456789

It may be the case that you want an approximate result. Then just go with float or double only:

dobule x = Double.parseDouble(a.getText());
dobule y = Double.parseDouble(b.getText());
res.setText("=" + (x/y));

Upvotes: 1

skiwi
skiwi

Reputation: 69249

It is possible that the app is crashing, because BigDecimal.toString() does something unexpected. Also a, or b or rx may be null.

In any way, I would consider using BigDecimal with the String constructor, such that no rounding errors occur:

String x = a.getText().toString();
String y = b.getText().toString();
BigDecimal xx = new BigDecimal(x);
BigDecimal yy = new BigDecimal(y);
BigDecimal rx = xx.divide(yy);
res.setText("=" + rx.toPlainString());

Also write new BigDecimal(x) instead of new BigDecimal (x). Note the omitted space, that may be the very reason why your app crashes, it is not allowed in Java.

Upvotes: 3

Related Questions