Mascara for money on android

0

I'm creating a function for when the user types in a EditText , it returns me with a chew in the field,

Example:

  • Type 1 returns "$ 0.01"
  • Type 11 returns "$ 0.11" and and so on

I tried this way

  public static String addMask(final String textoAFormatar) {
        String formatado = "";
        int i = 0;

        if (textoAFormatar.length() == 1) {
            String mask = "R$ #.##";
            DecimalFormat format = new DecimalFormat("0.00");
            String texto = format.format(textoAFormatar);


            // vamos iterar a mascara, para descobrir quais caracteres vamos adicionar e quando...
            for (char m : mask.toCharArray()) {
                if (m != '#') { // se não for um #, vamos colocar o caracter informado na máscara
                    formatado += m;
                    continue;
                }
                // Senão colocamos o valor que será formatado
                try {
                    formatado += texto.charAt(i);

                } catch (Exception e) {
                    break;
                }
                i++;
            }

        }


        return formatado;
    }
    
asked by anonymous 22.02.2018 / 00:39

2 answers

4

Use the NumberFormat class to resolve this problem. It is a class of the SDK itself and is very easy to use.

Usage:

String money = NumberFormat.getCurrencyInstance().format(0.01);

Return:

R$ 0,01

The getCurrencyInstance() method returns the local currency of the device. If the device is using a EN site, the returned currency will be USD .

    
22.02.2018 / 02:52
1

I did not do all the possible tests, but I think one way to solve your problem is like this:

String str = textoAFormatar; // argumento da sua funcao

if (str.length() == 1) {
    str = "00" + str;
} else if (str.length() == 2) {
    str = "0" + str;
}   

int index = str.length() - 2;
return "R$" + str.substring(0, index) + "." + str.substring(index);

Also, I imagine the same result can be achieved with StringBuilder .

    
22.02.2018 / 02:26