Converting Float to String and String to Float using the IFormatProvider for Numbers.

Posted by vishalneeraj-24503 under .NET Framework category on | Points: 40 | Views : 498
Import System.Globalization Namespace and use InvariantCulture which is a special type of culture which is culture-insensitive.We should use this culture when you need culture-independent results, e.g. when you format or parse values in XML file.

using System.Globalization;
float num = 1.5f;
string str1 = num.ToString(CultureInfo.InvariantCulture.NumberFormat);
string str2 = num.ToString(CultureInfo.GetCultureInfo("de-DE").NumberFormat);

float num1 = float.Parse("1.5", CultureInfo.InvariantCulture.NumberFormat);
float num2 = float.Parse("1,5", CultureInfo.GetCultureInfo("de-DE").NumberFormat);
float num3 = float.Parse("1,5", CultureInfo.GetCultureInfo("en-US").NumberFormat);

Here,de-DE is a Language code for German - Germany.
en-US is a Language code for English - United States.

Response.Write(str1 + "<br/>" + str2 + "<br/>" + num1 + "<br/>" + num2 + "<br/>" + num3);

15.0 or 15

Comments or Responses

Login to post response