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 the CultureInfo instance first.

Get invariant or specific CultureInfo

Invariant culture is a special type of culture that is culture-insensitive. You should use this culture when you need culture-independent results, e.g. when you format or parse values in the XML file. The invariant culture is internally associated with the English language. To get invariant CultureInfo instance use static property CultureInfo.In­variantCulture.

To get specific CultureInfo instance use the static method CultureInfo.Get­CultureInfo 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 the property CultureInfo.Num­berFormat to get an IFormatProvider for numbers (the NumberFormatInfo object)

// 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"
// parse float from string
float num = float.Parse("1.5", CultureInfo.InvariantCulture.NumberFormat);
float num = float.Parse("1,5", CultureInfo.GetCultureInfo("de-DE").NumberFormat);

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post