C# 小数类型相等
C# 十进制类型的相等比较是否比其他浮点类型更有可能像我们直观地期望的那样工作?
Is the equality comparison for C# decimal types any more likely to work as we would intuitively expect than other floating point types?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想这取决于你的直觉。我假设有些人会认为 1 除以 3 的结果是分数 1/3,而其他人会更多地思考“哦,1 除以 3 不能表示为十进制数,我们必须决定保留多少位数字,我们选择 0.333"。
如果您以前一种方式思考,
Decimal
不会对您有太大帮助,但如果您以后一种方式思考,并且在需要时明确舍入,则更有可能是“直观地”的操作" 不受十进制舍入误差的影响,例如除以 10,将按照您的预期进行操作。对于大多数人来说,这比二进制浮点类型的行为更直观,在二进制浮点类型中,2 的幂表现良好,但 10 的幂则不然。I guess that depends on your intuition. I would assume that some people would think of the result of dividing 1 by 3 as the fraction 1/3, and others would think more along the lines of "Oh, 1 divided by 3 can't be represented as a decimal number, we'll have to decide how many digits to keep, let's go with 0.333".
If you think in the former way,
Decimal
won't help you much, but if you think in the latter way, and are explicit about rounding when needed, it is more likely that operations that are "intuitively" not subject to rounding errors in decimal, e.g. dividing by 10, will behave as you expect. This is more intuitive to most people than the behavior of a binary floating-point type, where powers of 2 behave nicely, but powers of 10 do not.基本上,没有。
Decimal
类型仅表示一种特殊的浮点数,旨在减少舍入误差,特别是在以 10 为基数的系统中。也就是说,Decimal
的内部表示实际上是以 10(十进制)为基数的,而不是通常的二进制。因此,它是一种更适合货币计算的类型——尽管当然不限于此类应用。从 MSDN 页面获取该结构:
Basically, no. The
Decimal
type simply represents a specialised sort of floating-point number that is designed to reduce rounding error specifically in the base 10 system. That is, the internal representation of aDecimal
is in fact in base 10 (denary) and not the usual binary. Hence, it is a rather more appropriate type for monetary calculations -- though not of course limited to such applications.From the MSDN page for the structure: