1

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); 
9
  • On what line(s) is/are the error(s) happening? Commented Dec 7, 2013 at 17:55
  • There isn't error.the app forced close and ... . but in 120/10 it answers correctly Commented Dec 7, 2013 at 17:57
  • Next time, if you really cannot debug the error from within Android, please first verify if your code block (if it requires no Android framework) is even running in normal Java. Commented Dec 7, 2013 at 17:59
  • I tried but the app forced close again. Commented Dec 7, 2013 at 18:04
  • 1
    We need a bit more than that. Post the full stack trace Commented Dec 7, 2013 at 18:08

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

new BigDecimal (x) is perfectly legal Java syntax (though not recomended by Code Conventions)
1

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)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.