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
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
}
When you want to convert a string to number, you need to be sure which format does the string use. E.g. in English, there is a decimal point (“43.27”), while in Czech, there is a decimal comma (“43,27”).
By default, the current locale is used; if you know the number uses the English conversion, you need to specify the culture explicitly, e.g.
Convert.ToDouble(txtBox.Text, CultureInfo.InvariantCulture);
精彩评论