Is using "Touint64()" to format string correct?

Asked

Viewed 79 times

4

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

It is a good pathic to use this method to format strings? There is a recommended way?

An example of the use:

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

1 answer

6


If it reaches 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 wouldn’t 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. Then I would not use this conversion and format as text even:

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

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Obviously it has several other forms.

I even think . NET needs a slightly better library for formatting text, only in numbers and dates. If I find any external library I put it here, but I don’t remember seeing anything. Just found a method of extension simple, but it can handle several scenarios.

Browser other questions tagged

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