String Format CPF on Android

Asked

Viewed 1,664 times

0

I have a CPF variable that is populated with a value that comes from the database (11122233344). Before giving setText(), I need it to be formatted in 111.222.333-44. How could I do this?

3 answers

2


Look I did so may not be the best way more help, the example I did was in eclipse but in java, is the same way on android, I know because I’ve done there, but of course disregard the part of Static the main class, I did this basic example because now I’m not with an android studio ide.

public class Teste {

    private static String CPF ;

    public static void main(String[] args) {
        String cpf= "12345678910";
        // 123.456.789-10
        setCPF(cpf.substring(0,3)+"."+cpf.substring(3,6)+"."+cpf.substring(6,9)+"-"+cpf.substring(9,11));

        System.out.println("CPF:"+getCPF());
    }

    public static String getCPF() {
        return CPF;
    }

    public static void setCPF(String cPF) {
        CPF = cPF;
    }

}

Since Cpf will always be default values, you will have no problem with substring, as you can see above for the test I did, I received the number of Cpf not formatted in a String, after I did that I took each part of Cpf using substring and was concatenating already formatting and setting in Cpf...

  • ninja ! worked perfectly

1

I share the response of my fellow Members, I have just one point to consider. At some point the CPF can be numerical and come without the zeros left, so I suggest checking first if we have 11 digits, to avoid an exception when trying to access point 11 with the substring.

Would something like this:

 public static String formatarCPF(String cpf){
    String cpfCompleto = StringUtils.leftPad(cpf, 11, '0');
    return cpfCompleto.substring(0,3)+"."+cpfCompleto.substring(3,6)+"."+cpfCompleto.substring(6,9)+"-"+cpfCompleto.substring(9,11);
}

If you don’t have access to Stringutils from Apache Commons, you can do this function manually:

 public static String leftPad(String texto, Integer tamanho, Character caracter){
    if(texto.length() < tamanho){
        StringBuilder sb = new StringBuilder(texto);
        for(int cont = 0; cont < (tamanho-texto.length()); cont ++){
            sb.insert(0, caracter);
        }
        return sb.toString();
    }
    return texto;
}

I believe that so you will avoid mistakes, that may arise.

1

the function that Rogers went through, worked perfectly.

I edited and stayed like this for android:

public static String cpf_formatado(String cpf) {
        cpf = cpf.substring(0,3)+"."+cpf.substring(3,6)+"."+cpf.substring(6,9)+"-"+cpf.substring(9,11);
        return cpf;
    }

Browser other questions tagged

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