将一个双变量转换为十进制

如何将一个 double投向 decimal,这是在做货币开发时使用的。 M去哪里?

decimal dtot = (decimal)(doubleTotal);
186199 次浏览

You only use the M for a numeric literal, when you cast it's just:

decimal dtot = (decimal)doubleTotal;

Note that a floating point number is not suited to keep an exact value, so if you first add numbers together and then convert to Decimal you may get rounding errors. You may want to convert the numbers to Decimal before adding them together, or make sure that the numbers aren't floating point numbers in the first place.

使用默认转换类: Convert.ToDecimal(Double)

您可以像这样将一个双精度数转换为小数,而不需要 M字面后缀:

double dbl = 1.2345D;
decimal dec = (decimal) dbl;

在声明新的字面十进制值时,应使用 M:

decimal dec = 123.45M;

(如果没有 M,123.45将被视为 double,不会编译。)

Convert.ToDecimal(the double you are trying to convert);

这是一个古老的问题,我确实利用了这里显示的一些答案。尽管如此,在我的特定场景中,我想要转换成 decimaldouble值通常比 decimal.MaxValue大。因此,我没有处理异常,而是编写了这个扩展方法:

    public static decimal ToDecimal(this double @double) =>
@double > (double) decimal.MaxValue ? decimal.MaxValue : (decimal) @double;

如果您不想麻烦处理溢出异常,并且如果发生这样的事情,您只想保持最大可能的值(我的情况) ,那么上述方法是有效的,但我知道,对于许多其他情况,这不是预期的行为,可能是异常处理将是必要的。