IFormatProvider for Numbers [C#]
This example shows how to convert float to string and string to float using IFormatProvider. To get IFormatProvider you need to get CultureInfo instance first.
Get invariant or specific CultureInfo
Invariant culture is a special type of culture which is culture-insensitive. You should use this culture when you need culture-independent results, e.g. when you format or parse values in XML file. The invariant culture is internally associated with the English language. To get invariant CultureInfo instance use static property CultureInfo.InvariantCulture.
To get specific CultureInfo
instance use static method CultureInfo.GetCultureInfo
with the specific culture name, e.g. for the
German language CultureInfo.GetCultureInfo("de-DE")
.
Format and parse numbers using the IFormatProvider
Once you have the CultureInfo instance use property CultureInfo.NumberFormat to get an IFormatProvider for numbers (the NumberFormatInfo object)
[C#]// format float to string float num = 1.5f; string str = num.ToString(CultureInfo.InvariantCulture.NumberFormat); // "1.5" string str = num.ToString(CultureInfo.GetCultureInfo("de-DE").NumberFormat); // "1,5"[C#]
// parse float from string float num = float.Parse("1.5", CultureInfo.InvariantCulture.NumberFormat); float num = float.Parse("1,5", CultureInfo.GetCultureInfo("de-DE").NumberFormat);
See also
- [C#] String Format for Double – format float numbers
- [C#] Culture Names – list of all culture names in .NET Framework
- float.ToString – MSDN – format number using IFormatProvider
- float.Parse – MSDN – parse string using IFormatProvider
- CultureInfo – MSDN – object with information about a culture
- CultureInfo.NumberFormat – MSDN – returns NumberFormatInfo which implements IFormatProvider for numbers