Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to Double C#

I have a field in DB which is float. My application is WindowsForm. I need to convert the value in textbox of the format 43.27 to double. When I do this COnvert.ToDouble(txtbox.Text) I get exception saying input string is wrong format. How to rectify this issue

like image 819
xaria Avatar asked Jul 09 '26 13:07

xaria


1 Answers

Try specifying a culture when parsing:

// CultureInfo.InvariantCulture would use "." as decimal separator
// which might not be the case of the current culture
// you are using in your application. So this will parse
// values using "." as separator.
double d = double.Parse(txtbox.Text, CultureInfo.InvariantCulture);

And to handle the error case for gracefully instead of throwing exceptions around you could use the TryParse method:

double d;
if (double.TryParse(txtbox.Text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
{
    // TODO: use the parsed value
}
else
{
    // TODO: tell the user to enter a correct number
}
like image 158
Darin Dimitrov Avatar answered Jul 12 '26 03:07

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!