简体   繁体   English

Convert.ToDouble()引发格式异常

[英]Convert.ToDouble() throws Format Exception

I am reading Data from an internal Database. 我正在从内部数据库读取数据。 The code assigns value read from the database to double. 该代码将从数据库读取的值赋给double。

if (Convert.ToDouble(PricefromString) == Price && PriceFound == false)

PricefromString has been read from the database. 已从数据库中读取PricefromString。

Most of the time the code works fine, but i get a FormatException, when the string value is an integer value. 大多数情况下,代码可以正常工作,但是当字符串值为整数值时,我会收到FormatException。 In this particular case, when PricefromString = 77, i get the format exception. 在这种特殊情况下,当PricefromString = 77时,我得到了格式异常。 I tried debugging and checked the input string to ToDouble() which is throwing the exception. 我尝试调试并检查了输入字符串到ToDouble(),这将引发异常。

Edit: PricefromString has a whitespace tab character at the end attached. 编辑:PricefromString在结尾处有一个空格标签字符。 It works perfectly fine when the string is a double value eg. 当字符串是双精度值时,例如,它工作得很好。 76.99, 77.01, but i get an FormatException error when price reaches an integer value. 76.99,77.01,但是当价格达到整数值时出现FormatException错误。

Any leads ? 有线索吗?

There might be something else, because if 77 is of String data type then definitely it will work. 可能还有其他原因,因为如果77是String数据类型,则肯定可以使用。
Check to see if it does not contain any other characters like currency symbols. 检查它是否不包含任何其他字符,例如货币符号。

Double.Parse or Convert.ToDouble will throw an exception if it cannot parse the given value. Double.ParseConvert.ToDouble无法解析给定值,则将引发异常。

Whereas Double.TryParse returns a bool indicating whether it succeeded. Double.TryParse返回一个bool指示是否成功。

Try this: 尝试这个:

double value;
Double.TryParse(PricefromString, out value);

By this, you can check if it'll work or not and then do the real conversion once value is boolean true . 这样,您可以检查它是否可以工作,然后在value是boolean true进行真正的转换。

For more on this, please refer this answer: Parse v. TryParse 有关此的更多信息,请参考以下答案: Parse v。TryParse

but i get a FormatException, when the string value is an integer value. 但是当字符串值为整数值时,我得到了FormatException。 In this particular case, when PricefromString = 77, i get the format exception. 在这种特殊情况下,当PricefromString = 77时,我得到了格式异常。

No, you don't. 不,你没有。 Convert.ToDouble will work just fine with a string representing an integer, as you can see for yourself by running this code: 您可以通过运行以下代码亲自看到Convert.ToDouble与代表整数的字符串一起使用的效果:

Console.WriteLine(Convert.ToDouble("77"));

It does in fact print out 77. 实际上它确实打印出77。

I would urge you to take a long, hard look at what precisely your input string is. 我敦促您仔细检查一下您的输入字符串的确切含义。

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

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