Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format consider locale or not?

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!

like image 860
thethanghn Avatar asked Jul 30 '09 02:07

thethanghn


People also ask

What is locale in string format?

locale which is the locale value to be applied on the this method. format which is the format according to which the String is to be formatted. args which is the number of arguments for the formatted string. It can be optional, i.e. no arguments or any number of arguments according to the format.

Which format is used for string?

The java string format() method returns the formatted string by given locale, format and arguments. If you don't specify the locale in String.format() method, it uses default locale by calling Locale.getDefault() method.

Should I use string format?

Avoid using String. format() when possible. It is slow and difficult to read when you have more than two variables.

What is locale date format?

Java DateFormat The locale is used for specifying the region and language for making the code more locale to the user. The way of writing date is different in different regions of the world.


2 Answers

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.

like image 105
Eric Avatar answered Sep 22 '22 10:09

Eric


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.

like image 33
Robert Paulson Avatar answered Sep 18 '22 10:09

Robert Paulson