While Converting Decimal to String, I tried two methods.
Method 1:
string a = "100.00", b = "50.00";
string Total = (string)(Convert.ToDecimal(a) + Convert.ToDecimal(b));
It throws error, cannot convert Decimal to String.
Method 2:
string Total = (Convert.ToDecimal(a) + Convert.ToDecimal(b)).ToString();
It doesn't throw error and it is working fine.
I want to know the difference between these two methods of Conversion and Why it throws error when I used Method 1?
The first method is trying to take a decimal (the result of adding the 2 decimals) and cast it as a string. Since there's no (implicit or) explicit conversion from decimal to string, it throws because of the mismatch.
The second one takes a decimal and calls a ToString() method on it - since ToString is a valid method on the decimal type, this makes a normal instance method call and you get the return value of that call, which is a string.
Since you're using Convert calls already, you might find it more natural to do Convert.ToString to get the decimal back to a string.
It might be more clear if you separate the 'add two decimals' to a separate local var, since that's common to both here.
So, the (commented out) total1 fails because it's trying to just cast, and we have no conversion available to do so. The latter two both work fine, since they are method calls that are returning a string.
string a = "100.00", b = "50.00";
decimal result = Convert.ToDecimal(a) + Convert.ToDecimal(b);
//string total1 = (string)result;
string total2 = result.ToString();
string total3 = Convert.ToString(result);
The first code tries to "type cast" a decimal to string, where as the second one calls the ToString method on decimal to get the string representation of decimal. Type casting from decimal to string won't work, unless decimal type overloads the type conversion operator which it doesn't and hence the type casting throws exception.
Type casting in this case is like asking the CLR system to type cast a decimal to string, which CLR is unable to do because it doesn't find a way to do it.
Calling ToString is asking the decimal type to returns its string representation
Method1 is a cast , so you are trying to 'read' the data contained in a decimal variable as a string...of course you can't. You can cast, for example, a byte to an int because they are both numbers. Instead for decimal to string you need an explicit conversion procedure.
its because in first method you converted string a and b into decimal but while then you are just type casting to string, you need to convert that decimal value into string before assigning it to string variable.
in second method you are actually converting decimal value into string by using ToString() method, so its not giving error.
Here is link of table which says you can not convert decimal to string as you did in first method :
Explicit Numeric Conversions Table (C# Reference)
Second method is working because you are using the ToString() method of the object class.
In the first method are you basically doing
string a = (string)150m;
where 150 is decimal. There is no explicit or implicit cast from decimal to string. Compiler will not understand how to do the convert.
In the second method you call
string a = 150m.ToString();
In this case you are calling ToString method that Decimal class implements (along with all other classes).
Related
Convert.ToInt32 behaves different when passed string vs float/double literal
var result = Convert.ToInt32(12.4);//returns 12
result = Convert.ToInt32(12.44);//returns 12
result = Convert.ToInt32(12.4444444);//returns 12
result = Convert.ToInt32("12.4"); // Input string was not in a correct format.
I understand different overloads of Convert.ToInt32 are being called for string and float/double
The question is why this inconsistent behavior shouldn't single overload for Convert.ToInt32 throw an exception for loss of precision ?
The question is why this inconsistent behavior shouldn't single
overload for Convert.ToInt32 throw an exception for loss of precision
?
You can think of the utility methods you're currently using to convert from double to int as "casting" i.e (int)12.4, (int)12.44 etc. which in essence means you for sure know that there is high chance that you'll lose data precision, thus in short is like telling the compiler "go ahead and convert it as I don't mind data loss", so, no exception will be thrown whereas the last example that converts from string to int should throw an exception because according to MSDN:
ToInt32(String) method is equivalent to passing value to the
Int32.Parse(String).
and as we all know Int32.Parse(String) throws an exception if the specified string is not in the correct format.
The way I see it, when you start with an float/double and you convert to int you expect a loss of precision. When you have a string that you convert to int you don't expect the parsing to do any losing of data, you just want it to parse and fail if the string is not valid.
You first have to convert your string into double, then cast it to int. or do another convert to int.
result = Convert.ToInt32(Convert.ToDouble("12.4"));
From msdn Convert.ToInt32(string)
Converts the specified string representation of a number to an equivalent 32-bit signed integer.
https://msdn.microsoft.com/en-us/library/sf1aw27b(v=vs.110).aspx
In given examples you can see that converting from double representation to int gives format exception.
so this is clearly by design. you should do it right.
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
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?
I have this code in a shopping cart I am creating but I am receiving the error shown in the title.The error is showing up on this line:
Just call ToString to get a string representation of the decimal value:
order.Total = orderTotal.ToString("G");
Although I don't see why you would store the member Total as a string and not as a decimal too.
It sounds like the Order class has a Total property that's a string. Check the class definition for Order. If that's the case, I'd recommend changing the Total data type to a decimal, because having a currency value represented as a string doesn't make sense. decimal makes more sense.
How is your Order class looks like ? What is the type of the Property called Total ? It looks like it is a string type. Here you are trying to set decimal value to a string type That is y you are getting that error. So you need to convert decimal to string before assigning it to a string varaiable. Use the toString() method.
order.Total = orderTotal.ToString();
As Tudor already mentioned, It is better to use Total as a decimal property as it will be easy for you to do all mathematical operations. You dont need to convert it to decimal format every time you want to do an arithmetical operation and convert it again back to string
Change the type of Order.Total to Decimal. The data type Decimal does not automatically convert to string (and visa-versa) which is why you're getting an error, plus, any subsequent calls to Order.Total would be string related, so you would not be able to use operators like Order.Total +=
Also note that any binding convenience like a DataTable's 'format' property would be ignored because the underlying architecture won't call string.ToString(format).
I've got a LINQ query in VB:
Dim ss = _someClassDataSource.Sum(Function(s) TryCast(s, SomeClass).BreakdownCover)
where BreakdownCover's type is string. When I'm trying rewrite it in C#:
var ss = _someClassDataSource.Sum(s=>s.BreakdownCover);
I get the exception:
Cannot implicitly convert type 'string' to 'int'
How can I deal with this problem?
use Int.Parse, don't cast a string to an int
var ss=_someClassDataSource.Sum(s=>int.Parse(s.BreakdownCover));
If you're doing VB.NET then use
var ss=_someClassDataSource.Sum(s=>Integer.Parse(s.BreakdownCover));
Here is why you can't cast string to int:
Because the explicit cast isn't implemented... ToString() is a general
method (implemented in System.Object) and if string would implement
the cast that would beg the question if all other classes need to
implement it too...
It would potentially be better to not use Convert.ToInt32() because Convert.ToInt32 will still return a value when the string is null while int.Parse will throw. You might get unexpected results with Convert.ToInt32. Also see this question Whats the main difference between int.Parse() and Convert.ToInt32
Of course, this is based on the context as #Andy has pointed out. If you are ok with NULL being treated as 0 then either method will work.
You need to explicitly convert the string to an int:
var ss=_someClassDataSource.Sum(s=> Convert.ToInt32(s.BreakdownCover));
As pointed out by DustinDavis Convert.ToInt32 will return a 0 if the string is null. If you would rather an exception be thrown then Int32.Parse will be a better option. However if the field accepts nulls and if these should be treated as 0 then this will return the expected result.