Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Float that has period instead of comma?

Tags:

c#

.net

.net-2.0

I have data from a table in a database (string) that contain text and price. I extract the price from the data but my problem is that sometime I can Convert it to float and sometime not.

I have noticed that :

Convert.ToSingle(m.Groups[1].Value);

It works but not always because sometime the period is the problem (it requires a comma). What can I do? I have try to replace the ".", by "," but sometime on other PC it's a period that it's required!

like image 555
Mister Dev Avatar asked Dec 11 '08 13:12

Mister Dev


2 Answers

You have this problem because the conversion check the language of your PC. You will need to do something like :

Convert.ToSingle(m.Groups[1].Value, CultureInfo.InvariantCulture.NumberFormat);

This ways, it won't check the language of the PC. You can find more information about InvariantCulture from MSDN. I have something similar in a project and my conversion works.

like image 167
Patrick Desjardins Avatar answered Sep 30 '22 10:09

Patrick Desjardins


Or ask for this specific number format explicitly:

System.Globalization.NumberFormatInfo nf
  = new System.Globalization.NumberFormatInfo ( )
{
  NumberGroupSeparator = "."
};
float f = float.Parse ( "5.34534", nf );
like image 35
baretta Avatar answered Sep 30 '22 11:09

baretta