将双精度变量转换为十进制
如何将double
转换为decimal
(在货币开发时使用)。 M
去了哪里?
decimal dtot = (decimal)(doubleTotal);
How does one cast a double
to decimal
which is used when doing currency development. Where does the M
go?
decimal dtot = (decimal)(doubleTotal);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您仅将
M
用于数字文字,当您转换它时,它只是:请注意,浮点数不适合保留精确值,因此如果您首先将数字相加,然后转换为 < code>Decimal 你可能会得到舍入错误。您可能需要在将数字相加之前将其转换为
十进制
,或者首先确保这些数字不是浮点数。You only use the
M
for a numeric literal, when you cast it's just: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 toDecimal
before adding them together, or make sure that the numbers aren't floating point numbers in the first place.您可以像这样将双精度型转换为十进制数,而不需要
M
文字后缀:在声明新的文字十进制值时,应该使用
M
:(没有
M
>M, 123.45 被视为双精度数,无法编译。)You can cast a double to a decimal like this, without needing the
M
literal suffix:You should use the
M
when declaring a new literal decimal value:(Without the
M
, 123.45 is treated as a double and will not compile.)使用默认转换类:
Convert.ToDecimal(Double)
use default convertation class:
Convert.ToDecimal(Double)
嗯,这是一个老问题,我确实利用了这里显示的一些答案。然而,在我的特定场景中,我想要转换为
decimal
的double
值可能通常大于decimal.MaxValue
。因此,我编写了这个扩展方法,而不是处理异常:如果您不想费心处理溢出异常,并且如果发生这种情况,您只想保留最大可能值(我的情况),则上述方法有效,但我知道对于许多其他场景,这不是预期的行为,可能需要异常处理。
Well this is an old question and I indeed made use of some of the answers shown here. Nevertheless, in my particular scenario it was possible that the
double
value that I wanted to convert todecimal
was often bigger thandecimal.MaxValue
. So, instead of handling exceptions I wrote this extension method:The above approach works if you do not want to bother handling overflow exceptions and if such a thing happen you want just to keep the max possible value(my case), but I am aware that for many other scenarios this would not be the expected behavior and may be the exception handling will be needed.