Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert integer to string using current culture in .NET?

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 = "'"
like image 230
Ian Boyd Avatar asked Nov 30 '11 21:11

Ian Boyd


1 Answers

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"));
like image 97
Jon Skeet Avatar answered Sep 30 '22 13:09

Jon Skeet