-1

I have two EditTexts:

<EditText
    android:id="@+id/edit_text_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0.35" />

<EditText
    android:id="@+id/edit_text_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0.3" />

and I parseDouble these EditTexts:

EditText e1 = (EditText) findViewById(R.id.edit_text_1);
EditText e2 = (EditText) findViewById(R.id.edit_text_2); 
double a1 = Double.parseDouble(e1.getText().toString())
double a2 = Double.parseDouble(e2.getText().toString());
Log.e("a1", a1 + "");
Log.e("a2", a2 + "");
Log.e("Result", (a1 - a2) + "");

0.35 - 0.3 = 0.05 but the result is:

12-06 13:14:00.816 11557-11557/com.example.android.test E/a1: 0.35
12-06 13:14:00.816 11557-11557/com.example.android.test E/a2: 0.3
12-06 13:14:00.816 11557-11557/com.example.android.test E/Result: 0.04999999999999999

Why is this happening?

Wtower
  • 18,848
  • 11
  • 103
  • 80
  • 2
    Have a look at this question. http://stackoverflow.com/questions/322749/retain-precision-with-double-in-java. And try to use BigDouble data type as suggested by accepted answer. – Jabir Dec 06 '15 at 06:26
  • 1
    Do some research before asking a question. It will help you in developing your skills – Shvet Chakra Dec 06 '15 at 06:30

1 Answers1

0

Try this

EditText e1 = (EditText) findViewById(R.id.edit_text_1);
EditText e2 = (EditText) findViewById(R.id.edit_text_2); 
double a1 = Double.parseDouble(e1.getText().toString())
double a2 = Double.parseDouble(e2.getText().toString());
Log.e("a1", a1 + "");
Log.e("a2", a2 + "");
Log.e("Result", String.format("%.2f", (a1-a2) + ""));
M.Muzammil
  • 643
  • 9
  • 18