Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass double value to a textview in Android

In Android, I am setting the text of a textview to be the answer to a calculation which is a double data type.

When the double value has a value of 5, the textview receives the string: 5.0.

Code:

double result = number1/number2;
String finalresult = new Double(result).toString();
textView1.setText(finalresult);

How do I format the textView text so that it shows the double value in a consistent format?

like image 202
Matt9Atkins Avatar asked Apr 03 '12 17:04

Matt9Atkins


2 Answers

In Android, assign a double to a textView:

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));
like image 192
Arpit Patel Avatar answered Nov 09 '22 21:11

Arpit Patel


The best way is

   String finalresult = String.valueof(result); 
   textview.setText(finalresult);
like image 45
MAC Avatar answered Nov 09 '22 21:11

MAC