问题描述
.NET中的decimal
、float
和double
有什么区别?
What is the difference between decimal
, float
and double
in .NET?
什么时候有人会使用其中之一?
When would someone use one of these?
推荐答案
float
和 double
是 浮动二进制点类型.换句话说,它们代表这样一个数字:
float
and double
are floating binary point types. In other words, they represent a number like this:
10001.10010110011
二进制数和二进制点的位置都在值内编码.
The binary number and the location of the binary point are both encoded within the value.
decimal
是 浮动 decimal 点输入.换句话说,它们代表这样一个数字:
decimal
is a floating decimal point type. In other words, they represent a number like this:
12345.65789
同样,decimal 点的数字和位置都被编码在值中——这就是 decimal
仍然是浮点类型而不是定点类型的原因.
Again, the number and the location of the decimal point are both encoded within the value – that's what makes decimal
still a floating point type instead of a fixed point type.
需要注意的重要一点是,人类习惯于以十进制形式表示非整数,并期望以十进制表示的精确结果;并非所有十进制数都可以用二进制浮点数精确表示——例如 0.1——因此,如果您使用二进制浮点值,您实际上会得到 0.1 的近似值.当使用浮点小数点时,您仍然会得到近似值——例如,1 除以 3 的结果无法精确表示.
The important thing to note is that humans are used to representing non-integers in a decimal form, and expect exact results in decimal representations; not all decimal numbers are exactly representable in binary floating point – 0.1, for example – so if you use a binary floating point value you'll actually get an approximation to 0.1. You'll still get approximations when using a floating decimal point as well – the result of dividing 1 by 3 can't be exactly represented, for example.
至于什么时候用:
对于自然精确小数"的值,最好使用
decimal
.这通常适用于人类发明的任何概念:财务价值是最明显的例子,但也有其他例子.例如,考虑给潜水员或溜冰者的分数.
For values which are "naturally exact decimals" it's good to use
decimal
. This is usually suitable for any concepts invented by humans: financial values are the most obvious example, but there are others too. Consider the score given to divers or ice skaters, for example.
对于更多的自然产物而无法真正测量精确的值,float
/double
更多合适的.例如,科学数据通常会以这种形式表示.在这里,原始值一开始就不是十进制精度",因此保持十进制精度"对于预期结果并不重要.浮点二进制点类型的处理速度比小数要快得多.
For values which are more artefacts of nature which can't really be measured exactly anyway, float
/double
are more appropriate. For example, scientific data would usually be represented in this form. Here, the original values won't be "decimally accurate" to start with, so it's not important for the expected results to maintain the "decimal accuracy". Floating binary point types are much faster to work with than decimals.
这篇关于.NET 中十进制、浮点和双精度的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!