How to create a mask for monetary value in an editText, real in case you format this way to save in database "20.99"?

1

How to create a mask for monetary value in an editText, in case you format this way to save in the database "20.99"? 1.99 20.99 300.99 1000.99 10000.99

    
asked by anonymous 04.10.2017 / 13:18

1 answer

0

There is an android event called addTextChangedListener for EditText with afterTextChanged methods that will do an action when text is changed, beforeTextChanged that will do an action before the text is changed and onTextChanged which will do an action in real time, and using the conversion method to $ post format link you can do the following way:

EditText searchTo = (EditText)findViewById(R.id.medittext);
searchTo.addTextChangedListener(new TextWatcher() {
    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        searchTo.setText(formatDecimal(Float.parseFloat(searchTo.getText())));
    } 
});

Money conversion method:

public String formatDecimal(float number) {
  float epsilon = 0.004f; // 4 tenths of a cent
  if (Math.abs(Math.round(number) - number) < epsilon) {
     return String.format("%10.0f", number); // sdb
  } else {
     return String.format("%10.2f", number); // dj_segfault
  }
}
    
04.10.2017 / 17:59