String.Format consider locale or not?

做~自己de王妃 提交于 2019-12-10 13:03:40

问题


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!


回答1:


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.




回答2:


This works.

IFormatProvider iFormatProvider = new System.Globalization.CultureInfo("es-ES");

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

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

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




回答3:


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)))


来源:https://stackoverflow.com/questions/1204164/string-format-consider-locale-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!