Mascara for money on android

Asked

Viewed 2,112 times

1

I am creating a function for when the user type in a EditText , he returns me with a masca in the field,

Example:

  • Typing 1 returns "R$ 0.01"
  • When typing 11 returns "R$ 0.11" and so on and so forth

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;
    }
  • 1

    Take a look in that library, I use it and it works right for this problem.

  • 2

    @Rogersmarques, please read the guides for OS beginners, especially the topic on the comments, at the point when one should or should not make comments.

  • @Rogersmarques , Starkoverflow serves for this, looking for professionals to help us with our beginner problems

  • @Grupocdsinformática perfect, worked perfect in the project !!!!!

2 answers

4

Use the class Numberformat to solve your problem. It is a class of the SDK itself and is very easy to use.

Use:

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

Return:

R$ 0,01

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

1

I haven’t run every possible test, but I believe one of the ways to solve your problem is:

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);

Moreover, I imagine that the same result can be achieved with Stringbuilder.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.