Question Getting array of digits from Decimal

VBobCat

Well-known member
Joined
Sep 6, 2011
Messages
137
Location
S?o Paulo, Brazil
Programming Experience
3-5
Hello People,

I wrote this function, which performs validation for a sort of Tax-ID number in my country:

Private Shared Function vCPF(ByVal num As Decimal) As Boolean
    If num Mod 11111111111 = 0 Or num > 99999999998 Then Return False
    Dim Dig As Integer() = (From c As Char In num.ToString("00000000000").ToCharArray Select Integer.Parse(c)).ToArray
    Dim DV1 As Integer = 11 - (Dig(0) * 10 + Dig(1) * 9 + Dig(2) * 8 + Dig(3) * 7 + Dig(4) * 6 + Dig(5) * 5 + Dig(6) * 4 + Dig(7) * 3 + Dig(8) * 2) Mod 11
    If DV1 > 9 Then DV1 = 0
    If Dig(9) <> DV1 Then Return False
    Dim DV2 As Integer = 11 - (Dig(0) * 11 + Dig(1) * 10 + Dig(2) * 9 + Dig(3) * 8 + Dig(4) * 7 + Dig(5) * 6 + Dig(6) * 5 + Dig(7) * 4 + Dig(8) * 3 + Dig(9) * 2) Mod 11
    If DV2 > 9 Then DV2 = 0
    Return Dig(10) = DV2
End Function


It works fine, but I am curious to know if there is a better (that is shorter, more elegant, more straightforward) way to get an array of exact 11 digits from the Decimal-typed parameter, than the mixture of LINQ and parsing I made on the expression:
(From c As Char In num.ToString("00000000000").ToCharArray Select Integer.Parse(c)).ToArray[/CODE]

Thank you very much!
 
If there aren't fractions in the tax number that should be Long, not Decimal. That will also save you some chars formatting the number.
Declaring the data type for Dig and c variables is also not necessary, they can be inferred - more chars saved.
Further you do need to convert the numeric value to String, but converting that to Char array is not needed, a String is already an enumerable of Char.
Dim dig = (From c In num.ToString Select Integer.Parse(c)).ToArray

One more, you could use Int32 instead of Integer, but I wouldn't do that. Integer is the VB data type, while Int32 is the CLR structure representing it.
 
Yes, thank you very much! I think I'll just keep num.ToString("00000000000") because validation requires eleven digits, so if the number is less than 10000000000, and it can be, the proper leading zeros must be present. I'm happy to know my LINQ approach is no craze of mine.
 
Back
Top