字符串转换为双C# [英] Convert string to Double C#
本文介绍了字符串转换为双C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在数据库字段是浮动。我的应用程序是WindowsForm。我需要的值转换格式43.27的文本框一倍。
当我这样做COnvert.ToDouble(txtbox.Text)我得到异常说输入的字符串格式错误。
如何解决这个问题,
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);
和处理错误的情况下正常,而不是抛出异常的周围,你可以使用的TryParse 方式:
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
}
这篇关于字符串转换为双C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文