Jun 24, 2012

(C#) How to parse float numbers with IFormatProvider?

1 comment

IFormatProvider for Numbers in C#

 The following example shows how to convert float to string and vice-versa 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.In­variantCulture.
To get specific CultureInfo instance use static method CultureInfo.Get­CultureInfo with the specific culture name,
e.g. for the German language 
Code:
CultureInfo.GetCultureInfo("de-DE");

Format and parse numbers using the IFormatProvider

Once you have the CultureInfo instance, use property CultureInfo.Num­berFormat to get an IFormatProvider for numbers (the NumberFormatInfo object).

1. Float to String
Code:
// 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"

2. String to Float
Code:
/ parse float from string
float num = float.Parse("1.5", CultureInfo.InvariantCulture.NumberFormat);
float num = float.Parse("1,5", CultureInfo.GetCultureInfo("de-DE").NumberFormat);

If you feel this is helpful or you like it, Please share this using share buttons available on page.

1 comment :