Search code examples
androideclipsedouble

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?


Solution

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