johntrepreneur
johntrepreneur

Reputation: 4704

How to add thousands separator to a numeric string in c#?

I want this "123456789" to this "123,456,789".

Plenty of SO answers on how to format non-string types numerically using .Format() and .ToString(). Can't find any answers on how to do coming from a numeric string.

I can do this way, but it's not ideal:

Convert.ToInt32(minPrice).ToString("N0");

Upvotes: 3

Views: 7906

Answers (1)

alexbchr
alexbchr

Reputation: 613

Simply encapsulate your function, which you find isn't ideal, into an extension method.

public static string ToFormattedThousands(this string number)
{
    return Convert.ToInt32(number).ToString("N0");
}

Simply put this function into a static class and then you will be able to call it on any string.

For example :

string myString = "123456789".ToFormattedThousands();

Upvotes: 9

Related Questions