views:

1368

answers:

4

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!

+7  A: 

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.

Daok
You beat me by 17 seconds! You dont actually need to NumberFormat property as CultureInfo already implements IFormatProvider.
leppie
:P I have increase my typing since I am participating at SO ;)
Daok
A: 

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...)

Lette
Just restating what has been said will not gain you any more rep.
leppie
@leppie, I think I actually added some value. And, not getting any upvotes won't gain me any rep either.
Lette
I agree that value *was* added with the explanation of the NumberFormat requirement.
ZombieSheep
I do not have write access to the database.
Mister Dev
@Mister Dev: The recommendation of using InvariantCulture when storing and serialising still stands. (As @ICR says...)
Lette
A: 

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
A: 

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