Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
like image 344
johntrepreneur Avatar asked Dec 21 '25 05:12

johntrepreneur


1 Answers

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();
like image 74
alexbchr Avatar answered Dec 23 '25 18:12

alexbchr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!