Muhammad Umar Muhammad Umar - 6 months ago 55
Java Question

making EditText to show only two decimal places

i want to show only two decimal places in my edit text, ofc i wanna show currency in edit text but limiting its value to 2 digits after decimal.

I have seen some solutions using regular expression but i don't wanna do that. I HAVE been told that java support some internal library functions that can do that. Any one can please give me hints or give me some efficient code for that.

Regards

amount.setRawInputType(Configuration.KEYBOARD_12KEY);

amount.addTextChangedListener(new TextWatcher()
{

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
DecimalFormat formatVal = new DecimalFormat("##.##");
String formatted = formatVal.format(s);
amount.setText(formatted);

}

Answer

You can simply use DecimalFormat

DecimalFormat format = new DecimalFormat("##.##");
String formatted = format.format(22.123);
editText.setText(formatted);

You will get result in EditText as 22.12

Comments