简体   繁体   English

将字符串转换为Double C#

[英]Convert string to Double C#

I have a field in DB which is float. 我在DB中有一个字段是浮动的。 My application is WindowsForm. 我的应用程序是WindowsForm。 I need to convert the value in textbox of the format 43.27 to double. 我需要将格式为43.27的文本框中的值转换为double。 When I do this COnvert.ToDouble(txtbox.Text) I get exception saying input string is wrong format. 当我这样做时,COnvert.ToDouble(txtbox.Text)出现异常,提示输入字符串格式错误。 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: 而要妥善处理错误情况,而不是在周围抛出异常,可以使用TryParse方法:

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. 要将字符串转换为数字时,需要确保字符串使用哪种格式。 Eg in English, there is a decimal point (“43.27”), while in Czech, there is a decimal comma (“43,27”). 例如,英语中有一个小数点(“ 43.27”),而在捷克语中有一个小数点逗号(“ 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, eg 如果您知道数字使用英文转换,则需要明确指定文化,例如

Convert.ToDouble(txtBox.Text, CultureInfo.InvariantCulture);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM