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!
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.
Or ask for this specific number format explicitly:
System.Globalization.NumberFormatInfo nf
= new System.Globalization.NumberFormatInfo ( )
{
NumberGroupSeparator = "."
};
float f = float.Parse ( "5.34534", nf );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With