Converting an integer to a string according to the current regional settings in an UWP application

Jürgen Schmitz 20 Reputation points
2023-01-18T16:43:40.6266667+00:00

Hi,

I have the following example code in an UWP application:

int number = 1234;
string str = number.ToString("N0");

var cultureInfo = CultureInfo.CurrentCulture;

I have also selected German "de-DE" in my regional settings in Windows (default regional format).

However str is "1,234" in this example and cultureInfo is "en-US".

It should be "1.234" and "de-DE".

How can I fix this?

Thanks

Jus

Developer technologies Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. Junjie Zhu - MSFT 21,646 Reputation points
    2023-01-19T09:16:34.14+00:00

    Hello,

    Here is a workaround that can get the correct CultureInfo.

    1. Use GlobalizationPreferences.Languages to get current Language setting and convert it to CultureInfo.
    2. Use Windows.Globalization.NumberFormatting.DecimalFormatter to convert the number to the correct format.
    var cultureInfo= new System.Globalization.CultureInfo(Windows.System.UserProfile.GlobalizationPreferences.Languages[0]);
               
    var valueToBeFormatted = 1234567891.23;
    
    string currentLanguage= cultureInfo.Name;
    string currentRegion = Windows.System.UserProfile.GlobalizationPreferences.HomeGeographicRegion;
    
    // In this case it's the Euro with the default number formatting for Germany.
    var DecimalFormatEuroDE = new Windows.Globalization.NumberFormatting.DecimalFormatter(new[] { currentLanguage }, currentRegion);
    DecimalFormatEuroDE.IsGrouped = true;
    var DecimalValueEuroDE = DecimalFormatEuroDE.Format(valueToBeFormatted);
    
    // Results for display.
    var results = "Fixed number (" + valueToBeFormatted + ")\n" +
                    "Formatted Euro (de-DE defaults): " + DecimalValueEuroDE;
    Debug.WriteLine(results);
    

    Thank you


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.