String Format CPF on Android

0

I have a CPF variable that is populated with a value that comes from the database (% w / w). Before giving 11122233344 , I need to be formatted as setText() . How could I do this?

    
asked by anonymous 21.02.2018 / 14:11

2 answers

2

I've done so may not be the best way, but the example I did was in eclipse but in java, it's the same way on android, I know why I did it, but of course I disregard the static part of the class , I made this basic example because now I'm not with an ide android studio.

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

}

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

    
21.02.2018 / 15:50
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;
    }
    
21.02.2018 / 21:14