将双精度变量转换为十进制

发布于 2024-11-07 07:31:43 字数 148 浏览 0 评论 0原文

如何将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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

对风讲故事 2024-11-14 07:31:43

您仅将 M 用于数字文字,当您转换它时,它只是:

decimal dtot = (decimal)doubleTotal;

请注意,浮点数不适合保留精确值,因此如果您首先将数字相加,然后转换为 < code>Decimal 你可能会得到舍入错误。您可能需要在将数字相加之前将其转换为十进制,或者首先确保这些数字不是浮点数。

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.

驱逐舰岛风号 2024-11-14 07:31:43

您可以像这样将双精度型转换为十进制数,而不需要 M 文字后缀:

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

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

decimal dec = 123.45M;

没有 M >M, 123.45 被视为双精度数,无法编译。)

You can cast a double to a decimal like this, without needing the M literal suffix:

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

You should use the M when declaring a new literal decimal value:

decimal dec = 123.45M;

(Without the M, 123.45 is treated as a double and will not compile.)

指尖凝香 2024-11-14 07:31:43

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

use default convertation class: Convert.ToDecimal(Double)

不气馁 2024-11-14 07:31:43
Convert.ToDecimal(the double you are trying to convert);
Convert.ToDecimal(the double you are trying to convert);
何其悲哀 2024-11-14 07:31:43

嗯,这是一个老问题,我确实利用了这里显示的一些答案。然而,在我的特定场景中,我想要转换为 decimaldouble 值可能通常大于 decimal.MaxValue。因此,我编写了这个扩展方法,而不是处理异常:

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

如果您不想费心处理溢出异常,并且如果发生这种情况,您只想保留最大可能值(我的情况),则上述方法有效,但我知道对于许多其他场景,这不是预期的行为,可能需要异常处理。

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 to decimal was often bigger than decimal.MaxValue. So, instead of handling exceptions I wrote this extension method:

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文