Skip to content Skip to sidebar Skip to footer

Edittext Decimal Value

I'm implementing EditText's and I'm facing with one issue... I've put that the inputType is numberDecimal but at the time I type on the EditText I'd like to put the '.' or ',' auto

Solution 1:

All you have to do is something like this

finalDecialFormatdf=newDecimalFormat("#.00");

input.addTextChangedListener(newTextWatcher(){
    @OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {}

    @OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {}

    @OverridepublicvoidafterTextChanged(Editable s) {
        Stringvalue= s.toString();
        if(TextUtils.isEmpty(value)){
            // do what you want if it is emptyreturn;
        }

        try {
            DecimalFormatdf=newDecimalFormat("#.00");
            StringtestFormat= df.format(Double.parseDouble(s.toString()));

            // Manage the cursor positionint newPos;
            try {
                intpos= et.getSelectionStart();
                intsizeDiff= testFormat.length() - s.length();
                newPos = pos + sizeDiff;
            }catch(Exception e1){
                e1.printStackTrace();
                newPos = testFormat.length();
            }

            // Modify the edit text to hold the double value
            et.removeTextChangedListener(this);
            et.setText(testFormat);
            et.setSelection(newPos);
            et.addTextChangedListener(this);
        }catch(Exception e){
            e.printStackTrace();
            et.removeTextChangedListener(this);
            et.setText("");
            et.addTextChangedListener(this);
        }
    }
}

Modify the above code to do what you need, but this is the basic idea behind making sure the value is of decimal form. It is worth mentioning that when you modify text like this the cursor position is always a "fun" thing to try to get how you want it. What happens if you have "100.00" and someone puts the cursor in a place like "100.0|0" and presses 5. Should the result be "100.0|5" or "100.05|" and if it is the latter how do you handle them putting in the next value, do you use it to round the previous value? It is an interesting situation, but this will get you started.

Post a Comment for "Edittext Decimal Value"