10

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!

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Mister Dev
  • 10,021
  • 12
  • 41
  • 33

4 Answers4

22

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.

Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341
5

Or ask for this specific number format explicitly:

System.Globalization.NumberFormatInfo nf
  = new System.Globalization.NumberFormatInfo ( )
{
  NumberGroupSeparator = "."
};
float f = float.Parse ( "5.34534", nf );
baretta
  • 7,385
  • 1
  • 25
  • 25
3

If you don't have write access to the database the first thing to do is try and convince the sources of the data to use the invariant culture. If the data is being inputted by the user you can do something like:

float f = float.Parse(input);
string toDb = f.ToString(CultureInfo.InvariantCulture);

And then from the other side:

float f = float.Parse(fromDb, CultureInfo.InvariantCulture);
string toOutput = f.ToString();

Though if you can convince them of that it's probably better, as Lette says, to convince them to use the native data type.

I would also, as can be seen from the snippets above, recomment using float.Parse over Convert for a variety of reasons, but the most significant being the ability to use TryParse:

float f;
if (!float.TryParse(input, out f))
{
    // ERROR
}
ICR
  • 13,896
  • 4
  • 50
  • 78
0

As others have said:

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

You must also make sure that you use the InvariantCulture when writing to the database. (It would be even better if you saved the data to a column with its native data type, but I digress...)

Christoffer Lette
  • 14,346
  • 7
  • 50
  • 58