gpt4 book ai didi

c# - 为什么 Decimal.MaxValue 在 Single 和 Decimal 之间的转换不能传递?

转载 作者:行者123 更新时间:2023-11-30 15:24:23 27 4
gpt4 key购买 nike

如果我尝试将 Decimal.MaxValueDecimal 转换为 Single 并再次返回,转换将失败并出现 OverflowException:

Convert.ToDecimal(Convert.ToSingle(Decimal.MaxValue))
// '...' threw an exception of type 'System.OverflowException'
// base: {"Value was either too large or too small for a Decimal."}

什么给了? Decimal.MaxValue 作为 Single 的值肯定应该是有效的 Decimal 值吗?

我了解 SingleDecimal 之间的差异,预计从 Decimal 转换为 精度 会损失Single 但由于 Single.MaxValue 大于 Decimal.MaxValue 因此“Value was either too large or too small”没有意义为十进制”。如果您认为这确实有道理,请在回答中解释原因。

此外,

Convert.ToSingle(Decimal.MaxValue)
// 7.92281625E+28

因此将此数字转换为 Single 没有问题。

最佳答案

你做出了错误的假设:

Surely the value of Decimal.MaxValue as a Single should be a valid Decimal value?

Decimal.MaxValue 的值为 79,228,162,514,264,337,593,543,950,335float 无法表示接近该精度级别的任何位置,因此当您将 decimal 值转换为 float 时,您最终会得到一个近似值.

在这种情况下,float 在内部表示为 2^96。结果证明这是一个很好的近似值 -- 79,228,162,514,264,337,593,543,950,336 -- 但请注意最后一位数字。

float 的值大于 Decimal.MaxValue,这就是您尝试将其转换回 decimal 失败的原因。

(.NET 框架在尝试诊断此类问题时并没有提供太多帮助。它将始终为 float 显示预舍入值 -- 7.92281625E +28 或类似的——而且从来不是它在内部使用的完全近似值。)

关于c# - 为什么 Decimal.MaxValue 在 Single 和 Decimal 之间的转换不能传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32866708/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com