我有一个double类型的值,需要将其转换为十进制(decimal)。如果该值过大/过小,则结果应为decimal.MaxValue/decimal.MinValue。最佳方法是什么?
我想你应该意识到这是一种有损转换,如果可能的话应该避免使用。如果确实需要进行此操作:
private static readonly double MaxDecimalAsDouble = (double) decimal.MaxValue;
private static readonly double MinDecimalAsDouble = (double) decimal.MinValue;
...
public decimal ConvertWithCap(double input)
{
return input >= MaxDecimalAsDouble ? decimal.MaxValue
: input <= MinDecimalAsDouble ? decimal.MinValue
: (decimal) input;
}
double
值的方式来检查帽子,但然后硬编码返回被截断的十进制值。这避免了 double
无法准确表示 decimal
的最大/最小值的问题。(即使在 decimal
的最大规模下,连续整数也可以被表示-但对于 double
则不是这种情况。)decimal.MaxValue
不能被精确地表示为double
。 - Jon Skeetpublic decimal getDecimal(double value,double large,double small)
{
if(value <= large && value >= small)
return (decimal) value;
else if (value>large)
return decimal.MaxValue;
else
return decimal.MinValue;
}
这只是在网站上输入的,所以请原谅语法和拼写错误