C# and ToString()

When I do the following in C# in Unity I get an error:

123456.ToString("C");

Does Unity not support the various ToString formatting options offered by C#? As show here: Custom string formatting in C# | Aaron Johnson

How else then, can I format an integer with commas at every 3 digits?[/b]

It works fine.

Debug.Log (123456.ToString("C"));

No errors.

Well, it’s likely that you don’t actually want to use “C”; that’s for currency. You use

123456.ToString("#,#");

(Just to be pedantic, this isn’t C# string formatting, it’s .NET string formatting.)

–Eric

You can also check out the string.Format() method. I use that all the time.

Hmmmm… I swear I tried both methods for an hour last night and didn’t have any success.

I tried it now and it works on an integer like above, but it doesn’t work on a string like this:

("1234567").ToString("C");

Well, you can’t convert a string to a string. You can convert a string to an integer and then back to a string, or just use string.Format.

–Eric

Yup, figured out the problem. Apparently you can’t format a string with ToString, it’s got to be an int for float. So I’m converting the string to an int and then using System.String.Format

Are you saying there’s a way to get String.Format to work on strings without first converting to an int. I tried the following but got errors:

System.String.Format("0:0n", "123456");

What parameter can I use with String.Format to add commas after every 3 characters in a string?

It’s the N parameter for numbers with group separators (ie, the thousands commas). The numeric format strings are documented here.