Using ToUInt64 to format string is correct?

4

Looking for a practical way to format string I came across the following: Convert.ToUInt64(string).ToString(@"00000\-000") .

Is it a good practice to use this method to format strings ? Is there a recommended way?

Here is an example of the usage:

public class Program
{
    public static void Main()
    {
        var nomeCep = "JOSE - 09017092";
        var cep = nomeCep.Split('-')[1];
        Console.WriteLine(Convert.ToUInt64(cep).ToString(@"00000\-000"));
    }
}
  

Result: 09017-092

    
asked by anonymous 10.08.2016 / 22:48

1 answer

5

If you achieve the expected result in all situations I can not say it is wrong. But I consider gambiarra (which is sometimes the best way).

But I would not do that. Text is text, number is number. The fact that a text contains only numeric digits does not make it a number. Zip code is not used for calculations. I would always avoid treating them as if they were numbers under any circumstances. So I would not use this conversion and would format it as text itself:

var nomeCep = "JOSE - 09017092";
var cep = nomeCep.Split('-')[1];
WriteLine($"{cep.Substring(0, 6)}-{cep.Substring(6, 3)}");

See working on dotNetFiddle .

Obviously there are several other ways.

I even think that .Net needs a slightly better library for formatting text, only captioned in numbers and dates. If I find some external library I post here, but I do not remember seeing anything. Just I found a simple extension method , but it does handle various scenarios.

    
10.08.2016 / 23:09