August Williams
August Williams

Reputation: 929

How to parse a value obtained from NumericUpDown?

I have a NumericUpDown widget on my winform declared as numEnemyDefence. I want to use this to perform basic math on a variable:

damagePerHit -= Double.Parse(numEnemyDefence.Value);

Where damagePerHit is a double.

However, I am returned with the error of:

Cannot convert decimal to string.

Where is the string coming from? And why is the parse not working?

Upvotes: 0

Views: 1026

Answers (2)

Steve
Steve

Reputation: 216290

Double.Parse expects its argument to be a string. NumericUpDown.Value is a decimal. The C# compiler rejects your code because it doesn't make automatic conversions for you from the decimal type to the string type. And this is a good thing because it prevents a lot of subtle errors.

You can simply cast the decimal value to a double value

damagePerHit -= (double)numEnemyDefence.Value;

I also recommend to change (if possible) your variable damagePerHit to a simple decimal if you don't need the precision of a double value.
By the way these kind of operations are also source for other head scratching when you hit the floating point inaccuracy problem

Upvotes: 1

Chandrasekhar Raman
Chandrasekhar Raman

Reputation: 696

Use Convert class and Convert.toDouble method

Upvotes: 1

Related Questions