-4

Why I can not see the double value in a textView?

textView = (TextView) findViewById(R.id.textView);

double x = 5/2;

textView.setText(String.valueOf(x)); // I see this result as 2.0 and not as the 2.5
  • 2
    possible duplicate of [Division of integers in Java](http://stackoverflow.com/questions/7220681/division-of-integers-in-java) – user2864740 Sep 09 '15 at 19:32
  • http://stackoverflow.com/questions/18554032/how-to-get-the-full-fraction-value-of-a-division-result-in-java?lq=1 , http://stackoverflow.com/questions/24198620/why-variable-type-double-pi-22-7-returns-3-but-double-pi-22-0-7-or-22-7-0-r?lq=1 – user2864740 Sep 09 '15 at 19:33
  • (You will also want to format the number correctly or else you will run into 'odd cases'.) – user2864740 Sep 09 '15 at 19:35

3 Answers3

4

In Android TextView, you can use in that way, Use Double.toString:

result = number1/number2    
String stringdouble= Double.toString(result);
textview1.setText(stringdouble));

or you can use the NumberFormat:

Double result = number1/number2;
NumberFormat nm = NumberFormat.getNumberInstance();
textview1.setText(nm.format(result));

To force for 3 units precision:

private static DecimalFormat REAL_FORMATTER = new DecimalFormat("0.###");
textview1.setText(REAL_FORMATTER.format(result));
Arsal Imam
  • 2,882
  • 2
  • 24
  • 35
  • This misses out on the problem of `number1/number2` (where the numbers are both integers), but it does show how to *format a number for display* .. – user2864740 Sep 09 '15 at 19:36
3

You are seeing 2.0 because 5/2 is integer division. Change the line to double x = 5.0/2; or similar.

See this question for more.

Community
  • 1
  • 1
emerssso
  • 2,376
  • 18
  • 24
2

This should work double x = ((double) 5) /2.

Ashley Alvarado
  • 1,078
  • 10
  • 17