在.NET中,我该如何选择一个小数和双之间 [英] In .net, how do I choose between a Decimal and a Double
问题描述
我们这个讨论一天的工作,我希望能有一个问题,#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.)
- 在一个
双击<之间的区别是什么/ code>
和<一href="http://msdn.microsoft.com/en-us/library/system.decimal%28VS.71%29.aspx"><$c$c>Decimal$c$c>? - 当(在什么情况下),如果您的总是使用
双击
? - 当(在什么情况下),如果您的总是使用
十进制
? - 什么是驱动因素需要考虑的案件不属于两大阵营之一以上?
- What is the difference between a
Double
and aDecimal
? - 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二进制浮点类型文章和<一HREF =http://pobox.com/~skeet/csharp/decimal.html> .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.)
这篇关于在.NET中,我该如何选择一个小数和双之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!