在.NET中,我该如何选择一个小数和双之间小数、我该、如何选择、NET

2023-09-02 10:30:22 作者:愿时光厚待我爱人

我们这个讨论一天的工作,我希望能有一个问题,#1我会点人所以这里去。)

We were discussing this the other day at work and I wish there was a Stackoverflow question I would point people at so here goes.)

在一个 双击 和Decimal? 当(在什么情况下),如果您的总是使用双击? 当(在什么情况下),如果您的总是使用十进制? 什么是驱动因素需要​​考虑的案件不属于两大阵营之一以上? What is the difference between a Double and a Decimal? When (in what cases) should you always use a Double? When (in what cases) should you always use a Decimal? What’s the driving factors to consider in cases that don’t fall into one of the two camps above?

有很多重叠这个问题的问题,但他们往往会问:什么人应该做在一个给定的情况下,而不是如何决定在一般情况下。

There are a lot of questions that overlap this question, but they tend to be asking what someone should do in a given case, not how to decide in the general case.

推荐答案

我经常思考的自然的VS的人工的数量。

I usually think about natural vs artificial quantities.

自然数量是像体重,身高和时间。这些将永远不会被绝对精确的测量,并有很少的它绝对精确的算法任何想法:你不是一般应加起来的高度,然后在确认结果是完全按预期。使用对于这种数量。双打有一个巨大的范围内,但有限的precision;他们也非常快。

Natural quantities are things like weight, height and time. These will never be measured absolutely accurately, and there's rarely any idea of absolutely exact arithmetic on it: you shouldn't generally be adding up heights and then making sure that the result is exactly as expected. Use double for this sort of quantity. Doubles have a huge range, but limited precision; they're also extremely fast.

占主导地位的人工量就是金钱。有这样的事,作为究竟$ 10.52,而如果你添加48美分,收于它,你希望有确切$ 11使用十进制对于这种数量。理由:因为这是人为的,开始时,涉及的人数是人为太多,旨在满足人类的需求 - 这意味着他们pssed在基地10自然EX $ P $使存储重presentation匹配人重presentation。 十进制没有的范围双,但大多数的人工数量并不需要额外的范围内无论是。它比也比较慢,但我个人有这给了我正确的答案速度比一个错误的答案很快一个银行帐号:)

The dominant artificial quantity is money. There is such a thing as "exactly $10.52", and if you add 48 cents to it you expect to have exactly $11. Use decimal for this sort of quantity. Justification: given that it's artificial to start with, the numbers involved are artificial too, designed to meet human needs - which means they're naturally expressed in base 10. Make the storage representation match the human representation. decimal doesn't have the range of double, but most artificial quantities don't need that extra range either. It's also slower than double, but I'd personally have a bank account which gave me the right answer slowly than a wrong answer quickly :)

对于更多的信息,我有 .NET二进制浮点类型文章和 .NET小数类型。 (请注意,十进制是一个浮点类型太多 - 但有问题的点是小数点,而不是一个小数点)

For a bit more information, I have articles on .NET binary floating point types and the .NET decimal type. (Note that decimal is a floating point type too - but the "point" in question is a decimal point, not a binary point.)