Reputation: 1158
I am getting an error when I am trying to execute a stored procedure.
C# property - that I can't change :
private decimal? a;
public decimal? A
{
get { return a; }
set { a = value; }
}
C# DAC layer that I can change :
if (A.HasValue)
dict.Add("A", A.Value);
else
dict.Add("A", null);
In stored procedure input --> I can't change
@A decimal(6,0)
What is the best way to convert it without having exception and data loss? I need to do the same for @B decimal(8,2)
The database columns accepts nulls and decimal of above format.
Error I am getting:
Error converting data type numeric to decimal
Upvotes: 0
Views: 511
Reputation: 718
It's never mentioned which version of the language you're using, so I'm going to assume C# 6. You can remove the if/else statement and just use a single statement dict.Add("A", A?.Value)
. This is a Null Conditional Operator: https://msdn.microsoft.com/en-us/library/dn986595.aspx.
As far as how to convert and not lose data... This is typically not possible. If you have a number with 3 digits precision and you want 2 digits of precision, there is rounding associated with that which means the numbers will always be off a little bit. If you want to convert a number from say, 3 decimal places to 2 decimal places, simply put your value in to string.Format()
with the proper format specifier. If you want a number with no precision (a whole number), just take your decimal and store it in an integer type int myWholeNumber = myDecimal;
or convert (probably safer) int myWholeNumber = decimal.ConvertToInt32(myDecimal);
To convert a string to a decimal, just use the parse method. decimal myDecimal = decimal.Parse(myStringDecimalValue);
Upvotes: 1