1

I am reading Data from an internal Database. The code assigns value read from the database to double.

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

PricefromString has been read from the database.

Most of the time the code works fine, but i get a FormatException, when the string value is an integer value. In this particular case, when PricefromString = 77, i get the format exception. I tried debugging and checked the input string to ToDouble() which is throwing the exception.

Edit: PricefromString has a whitespace tab character at the end attached. 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.

Any leads ?

novice
  • 545
  • 3
  • 16

2 Answers2

2

There might be something else, because if 77 is of String data type then definitely it will work.
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.

Whereas Double.TryParse returns a bool indicating whether it succeeded.

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.

For more on this, please refer this answer: Parse v. TryParse

Community
  • 1
  • 1
Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
2

but i get a FormatException, when the string value is an integer value. In this particular case, when PricefromString = 77, i get the format exception.

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:

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

It does in fact print out 77.

I would urge you to take a long, hard look at what precisely your input string is.

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393