Format number
package app.test;
import java.text.NumberFormat;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Test extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
final EditText myEditField = (EditText) findViewById(R.id.mealprice);
final TextView answerfield = (TextView) findViewById(R.id.answer);
final Button button = (Button) findViewById(R.id.calculate);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
String mealprice = myEditField.getText().toString();
String answer = "";
if (mealprice.indexOf("$") == -1) {
mealprice = "$" + mealprice;
}
NumberFormat nf = java.text.NumberFormat.getCurrencyInstance();
if (nf == null) {
Log.i("", "NumberFormat is null");
}
float fmp = nf.parse(mealprice).floatValue();
fmp *= 2;
Log.i("", "Total:" + fmp);
answer = "Full Price:" + nf.format(fmp);
answerfield.setText(answer);
} catch (java.text.ParseException pe) {
Log.i("", "Parse exception caught");
answerfield.setText("Failed to parse amount?");
} catch (Exception e) {
Log.e("", "Failed to Calculate Tip:" + e.getMessage());
e.printStackTrace();
answerfield.setText(e.getMessage());
}
}
});
}
}
// main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Calculator"
/>
<EditText
android:id="@+id/mealprice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoText="true"
/>
<Button
android:id="@+id/calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate Tip"
/>
<TextView
android:id="@+id/answer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>
Related examples in the same category