7

How do i convert an integer to a localized string in .NET?

Exempli gratia:

Int64 value = 12345678901;

value.ToString();  
   // returns "12345678901", should be "123,4567,8901"

value.ToString(CultureInfo.CurrentCulture);  
   // returns "12345678901", should be "123,4567,8901"

value.ToString(CultureInfo.CreateSpecificCulture("en-US")) 
   // returns "12345678901", should be "12,345,678,901"

value.ToString(CultureInfo.CreateSpecificCulture("fr-CH"))
   // returns "12345678901", should be "12'345'678'901"

value.ToString(CultureInfo.CreateSpecificCulture("te-IN"))
   // returns "12345678901", should be "12,34,56,78,901"

How do i convert an integer (or float) to a localized string in .NET?

Bonus Chatter

Unique list of number formats in the world:

  • 12 345 678 901
  • 12,34,56,78,901
  • 12,345,678,901
  • 12.345.678.901
  • 12?345?678?901
  • 123,4567,8901
  • 12'345'678'901

Additional bonus information where these culture settings can be found in .NET:

CultureInfo.CreateSpecificCulture("en-US").NumberFormat.NumberGroupSizes = { 3 }
CultureInfo.CreateSpecificCulture("en-US").NumberFormat.NumberGroupSeparator = ","

CultureInfo.CreateSpecificCulture("te-IN").NumberFormat.NumberGroupSizes = { 3, 2 }
CultureInfo.CreateSpecificCulture("te-IN").NumberFormat.NumberGroupSeparator = ","

CultureInfo.CreateSpecificCulture("te-IN").NumberFormat.NumberGroupSizes = { 3 }
CultureInfo.CreateSpecificCulture("te-IN").NumberFormat.NumberGroupSeparator = "'"

1 Answer 1

10

Use the "N" standard format specifier with a precision of 0.

using System;

class Test
{
    static void Main() 
    {
        long value = 12345678901;
        string text = value.ToString("N0");
        Console.WriteLine(text);
    }
}

Result (on my UK machine):

12,345,678,901

That will take the current culture into account for various aspects. You can specify a culture separately, of course.

Edit: Generalized form for specific cultures:

value.ToString("N0", CultureInfo.CreateSpecificCulture("fr-CH"));
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.