Why does the conversion take place in the wrong way?

Asked

Viewed 58 times

2

When performing the conversion of a number I need to format it, and unfortunately it is not coming out the way I need it.

I need to format a number of 11 digits in CPF, but when putting the formatting, in the execution of the program, the formatting is "skipped". When putting "," it formats as money ex: "00,000,000,000,0-00" and if I put "." it doesn’t even format, and puts the - at the end of the text.

Follows the code:

 If Len(numcgc) = 11 Or Len(numcgc) = 14 Then

        Select Case Len(numcgc)
            Case 11
                If Not classe.CalculaCpf(numcgc) Then
                    MsgBox("ATENÇÃO! - N° do CPF inválido - Vefique")
                    TxtCgc.Select()
                    TxtCgc.Clear()
                    Exit Sub
                End If
                If IsNumeric(numcgc) Then TxtCgc.Text = Format(CLng(numcgc), "###,###,###-##")

1 answer

4


First, the data you are using is descriptive, that is, it is a text and should not convert to number under any circumstances, it is not a number, only coincidentally the text only has numerical digits.

And if to do conversion is not how it is done in VB.NET, this is something that old VB and should no longer be used. The correct way has already been answered in several questions here (although all in C#, it is the same thing), one of them.

So the right thing is:

TxtCgc.Text = numcgc.Substring(0, 3) + "." + numcgc.Substring(3, 3) + "." + numcgc.Substring(6, 3) + "-" + numcgc.Substring(9, 2)

I put in the Github for future reference.

In fact it needs to validate this data more, a lot can come wrong.

  • Thank you very much, your solution worked perfectly. I didn’t understand very well how the reference of the old Vb and the current... But I still thank you deeply!

  • @Jaderson Don’t use CLng().

Browser other questions tagged

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