3

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");
6
  • @SystemDown - Because it's already a string and converting it to an int then back to a string seems unnecessary just to return it to string in a different format. Commented Oct 3, 2013 at 0:32
  • The alternative will be to manually go through the string to find the appropriate places to insert the commas, which could potentially be even more costly. Commented Oct 3, 2013 at 0:36
  • 3
    In addition to plausibly being even more costly, it may also be open to error. For example, if it's not actually an integer (which would throw an exception that you could fix), or has leading zeros, or a negative sign, depending on your implementation, you may produce an incorrect result and never know about it. Commented Oct 3, 2013 at 0:38
  • 1
    This already seems like a simple/neat solution to your problem. Commented Oct 3, 2013 at 0:40
  • Thanks, I see. Then that would makes sense why I couldn't seem to find any documentation on it despite being such a simple task. If that's the recommended way, then I'll just stick with that. Commented Oct 3, 2013 at 0:43

1 Answer 1

9

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.