double? AssessmentTotal=2.345;
double? AssessmentTotalval = Math.Round((decimal)AssessmentTotal == null ? 0 : AssessmentTotal, 2);
我试图将双倍值整理一下。预期结果为2.35
我收到了构建错误。
错误40最佳重载方法匹配 ' System.Math.Round(double,int)'有一些无效的论点
答案 0 :(得分:4)
考虑到舍入是一种非廉价的操作,您可以:
double? AssessmentTotalval = AssessmentTotal == null ?
0.0 :
Math.Round(AssessmentTotal.Value, 2, MidpointRounding.AwayFromZero)
如果Math.Round
为AssessmentTotal
,则完全绕过null
。
请注意,此时AssessmentTotalval
总是!= null
,因此拥有double?
请注意,即使使用MidpointRounding.AwayFromZero
,否则0.005
将成为0
而不是0.01
。
答案 1 :(得分:2)
尝试这样做:
double? AssessmentTotal = 2.345;
double? AssessmentTotalval = Math.Round(AssessmentTotal.GetValueOrDefault(), 2);
您当前的方法存在许多问题。
首先,如果(decimal)AssessmentTotal == null
不为null,则条件AssessmentTotal
仅计算为true。只要它是null
,就会得到一个" InvalidOperationException:Nullabl对象必须有一个值。"例外。致电AssessmentTotal.GetValueOrDefault()
可以避免这个问题。
其次,Math.Round(...)
使用double
或decimal
- 使用0
使您的代码可读性降低(并且可能有错误)。您应始终使用0.0
double
或0m
decimal
。在您的情况下,您应该使用0.0
,因为您正在处理double
。
根据您的评论重新整理49.625
,您需要将代码更改为:
double? AssessmentTotal = 49.625;
double? AssessmentTotalval = Math.Round(AssessmentTotal.GetValueOrDefault(), 2, MidpointRounding.AwayFromZero);
MidpointRounding
默认值为MidpointRounding.ToEven
- 您需要MidpointRounding.AwayFromZero
。
答案 2 :(得分:2)
你可以像下面这样做。
double? AssessmentTotal=2.345;
double? AssessmentTotalval = AssessmentTotal.HasValue ? Math.Round(AssessmentTotal.Value,2) : (double?)null;
如果您想在AssessmentTotal为null时为0 然后你可以修改上面的代码如下。
double? AssessmentTotal=2.345;
double? AssessmentTotalval = AssessmentTotal.HasValue ? Math.Round(AssessmentTotal.Value,2) : (double?)0;
答案 3 :(得分:0)
double? AssessmentTotal=2.345;
double? AssessmentTotalval = Math.Round((decimal)AssessmentTotal == null ? 0
: AssessmentTotal.Value, 2);
Console.WriteLine(AssessmentTotalval);
**更正**
如果值为null,则上面的代码抛出错误。以下代码效果更好
double? AssessmentTotalval = AssessmentTotal != null ? Math.Round(AssessmentTotal.Value, 2) : 0;
答案 4 :(得分:-2)
double? AssessmentTotalval = Convert.ToDouble((AssessmentTotal ?? 0).ToString("N2"));