How to parse a value obtained from NumericUpDown? - c#

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?

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

Use Convert class and Convert.toDouble method

Related

How to handle System.FormatException if we don't know the data type

In a calculator application, I have to convert the string the user inputs to a data type, but I don't know if it is a float, integer, double, etc, and I wrote:
value += double.Parse(result.Text);
Whenever I write something like 12.25, it appears System.FormatException. However, if I write 2 or 89, the program runs without any problem.
I really don't know what to do, I've tried changing the double to float but the same error appears.
The safer way is to use TryParse
double.TryParse(string, out double)
Also keep in mind that parsing is culture related. To make sure your decimal separator is ., not , you could do something like this:
double.Parse(result.Text, CultureInfo.InvariantCulture)
TryParse is a good way, but is there a particular reason to not use Convert?
value += Convert.ToDouble(result.Text);
Of course, you could get into trouble if you're in places like Europe, where comma is used in place of a decimal point, in which case you need to allow for culture.

Getting "The best overloaded method match for double.Parse(string) has some invalid arguments" error

With this kind of code
double socialSecurityFee = 0;
double xsocialSecurityFee = double.Parse (socialSecurityFee);
I get this kind of error
Error CS1502: The best overloaded method match for
`double.Parse(string)' has some invalid arguments (CS1502)
(socialSecurityFee)
What's wrong with my code?
What's wrong with my code?
Exactly what the compiler is telling you - none of the overloads of double.Parse is appropriate for a single argument of type double. It's not even clear what you'd mean by that - parsing is usually about converting from one type (commonly a string) into another type (double in this case). Your initial value is already a double, so what would you expect it to do?
My guess is that you actually have a string somewhere, and you're trying to parse that - so you need to change your argument so that it uses that string instead of the socialSecurityFee variable. It's not clear that you need two variables of type double at all.
In addition, if this is meant to represent a currency amount (as it sounds like) you should consider using decimal instead of double.
double.Parse expects string as a parameter and you're trying to call it with another double value.
I'm not really sure why you're using double.Parse here, but to make it work add ToString() call:
double socialSecurityFee = 0;
double xsocialSecurityFee = double.Parse(socialSecurityFee.ToString());
or just assign the value itself (because it's already a double, isn't it?):
double socialSecurityFee = 0;
double xsocialSecurityFee = socialSecurityFee ;
There are four overloads of Double.Parse. Only one of them accepts a single parameter. The type of that parameter is a string but you are trying to pass a double. That is exactly what the compiler error message is telling you. You can not do that because doubles are not implicitly convertible to string. You can't invoke a method using parameters that don't implicitly convert to the types the method expects.
But what are you trying to do? socialSecurityFee is a double, so why are you trying to parse it? Parsing means analyzing a string to give it meaning.
The method double.Parse() expects a string argument, and you're passing it a double value.
Since your original value is already a double, you don't even need to use double.Parse()
socialSecurityFee is already a double. double.Parse expects a string, tough. You don't need to parse anything here. What are you trying to do?

Does (int)myDouble ever differ from (int)Math.Truncate(myDouble)?

Does (int)myDouble ever differ from (int)Math.Truncate(myDouble)?
Is there any reason I should prefer one over the other?
Math.Truncate is intended for when you need to keep your result as a double with no fractional part. If you want to convent it to an int, just use the cast directly.
Edit: For reference, here is the relevant documentation from the “Explicit Numeric Conversions Table”:
When you convert from a double or float value to an integral type, the value is truncated.
As pointed out by Ignacio Vazquez-Abrams (int)myDouble will fail in the same way as (int)Math.Truncate(myDouble) when myDouble is too large.
So there is no difference in output, but (int)myDouble is working faster.

How to format calculated value as decimal in mvc3/razor/webgrid?

How can I get this to show as a decimal in mvc3/razor/webgrid helper?
grid.Column("DecimalValue", format: #<text>#((#item.SomeInt / #item.SomeInt2))</text>)
You will need to cast to decimal, or you will only do integer arithmetic, which by definition returns an integer.
Not quite sure razor syntax will allow this (if not, use a code block #{})
#(decimal)item.SomeInt / #item.SomeInt2

C# Wrong conversion using Convert.ChangeType()

I am using Convert.ChangeType() to convert from Object (which I get from DataBase) to a generic type T. The code looks like this:
T element = (T)Convert.ChangeType(obj, typeof(T));
return element;
and this works great most of the time, however I have discovered that if I try to cast something as simple as return of the following sql query
select 3.2
the above code (T being double) wont return 3.2, but 3.2000000000000002. I can't realise why this is happening, or how to fix it. Please help!
What you're seeing is an artifact of the way floating-point numbers are represented in memory. There's quite a bit of information available on exactly why this is, but this paper is a good one. This phenomenon is why you can end up with seemingly anomalous behavior. A double or single should never be displayed to the user unformatted, and you should avoid equality comparisons like the plague.
If you need numbers that are accurate to a greater level of precision (ie, representing currency values), then use decimal.
This probably is because of floating point arithmetic. You probably should use decimal instead of double.
It is not a problem of Convert. Internally double type represent as infinite fraction of 2 of real number, that is why you got such result. Depending of your purpose use:
Either Decimal
Or use precise formating {0:F2}
Use Math.Flor/Math.Ceil

Categories

Resources