[英]Convert Decimal to decimal of a particular format?
I am getting an error when I am trying to execute a stored procedure. 尝试执行存储过程时出现错误。
C# property - that I can't change : C#属性-我无法更改:
private decimal? a;
public decimal? A
{
get { return a; }
set { a = value; }
}
C# DAC layer that I can change : 我可以更改的C#DAC层:
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)
我需要对
@B decimal(8,2)
做同样的事情
The database columns accepts nulls and decimal of above format. 数据库列接受上述格式的null和十进制。
Error I am getting: 我得到的错误:
Error converting data type numeric to decimal
将数据类型数字转换为十进制时出错
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)
. 从未提到您正在使用哪种语言版本,因此我将假设使用C#6。您可以删除if / else语句,而只使用一个语句
dict.Add("A", A?.Value)
。 This is a Null Conditional Operator: https://msdn.microsoft.com/en-us/library/dn986595.aspx . 这是一个空条件运算符: https : //msdn.microsoft.com/zh-cn/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.
如果您有一个精度为3位数字的数字,并且希望精度为2位数字,则与该数字相关联的舍入表示这意味着数字总是会有些许偏差。 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. 如果要将数字从3个小数位转换为2个小数位,只需使用适当的格式说明符将值放入
string.Format()
中即可。 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;
如果您想要一个没有精度的数字(整数),只需将您的十进制数存储在整数类型
int myWholeNumber = myDecimal;
or convert (probably safer) int myWholeNumber = decimal.ConvertToInt32(myDecimal);
或转换(可能更安全)
int myWholeNumber = decimal.ConvertToInt32(myDecimal);
To convert a string to a decimal, just use the parse method. 要将字符串转换为十进制,只需使用parse方法。
decimal myDecimal = decimal.Parse(myStringDecimalValue);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.