当减去两个数字时,结果会失败,来自java,android中的EditText的parseDouble

时间:2015-12-06 06:22:23

标签: java android

我有两个EditText s:

<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" />

parseDouble这些EditText s:

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但结果是:

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

为什么会这样?

1 个答案:

答案 0 :(得分:0)

试试这个

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