8

Is it true that String.Format works 2 ways: if we use built-in format such as C, N, P.... it will take locale settings into account? if we use custom format code such as #,##0.000 it will NOT take locale settings into account?

In my code, I use method like this

String.Format("{0:#.##0,000}", value);

because my country use comma as decimal separator

but the result still is: 1,234.500 as if it consider dot as decimal separator.

Please help!

Robert Paulson
  • 17,603
  • 5
  • 34
  • 53
thethanghn
  • 319
  • 2
  • 5
  • 21

3 Answers3

21

You want to use CultureInfo:

value.ToString("N", new CultureInfo("vn-VN"));

Using String.Format:

String.Format(new CultureInfo("vi-VN"), "N", value);

Since you're in Hanoi (from profile), I used Vietnam's code, which is vn-VN.

KwiZ
  • 1,364
  • 2
  • 15
  • 25
Eric
  • 92,005
  • 12
  • 114
  • 115
4

This works. The formatted value is 123.456,789 which is correct per es-ES

   IFormatProvider iFormatProvider = new System.Globalization.CultureInfo("es-ES");
   var value = 123456.789001m;

   string s = value.ToString("#,##0.000", iFormatProvider);

   string s2 = string.Format(iFormatProvider, "{0:#,##0.000}", value);

   FormattableString fs = $"{value:#,##0.000}";
   string s3 = fs.ToString(iFormatProvider);

Note that the , and . are using a 'standard' en-US style, but .ToString() and string.Format() with a format provider does the right thing.

Robert Paulson
  • 17,603
  • 5
  • 34
  • 53
0

You should make sure your thread uses the correct culture:

        Thread.CurrentThread.CurrentCulture = CultureInfo.CurrentCulture
        Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentCulture
        FrameworkElement.LanguageProperty.OverrideMetadata(GetType(FrameworkElement), New FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)))
viking_grll
  • 131
  • 8