.NET 中小数、浮点数和双精度数之间的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/618535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between decimal, float and double in .NET?
提问by Jon Skeet
What is the difference between decimal, floatand doublein .NET?
是什么区别decimal,float并double在.NET?
When would someone use one of these?
什么时候有人会使用其中之一?
回答by Jon Skeet
floatand doubleare floating binarypoint types. In other words, they represent a number like this:
float并且double是浮点二进制小数点类型。换句话说,它们代表一个这样的数字:
10001.10010110011
The binary number and the location of the binary point are both encoded within the value.
二进制数和二进制小数点的位置都在值中编码。
decimalis a floating decimalpoint type. In other words, they represent a number like this:
decimal是浮点小数点类型。换句话说,它们代表一个这样的数字:
12345.65789
Again, the number and the location of the decimalpoint are both encoded within the value – that's what makes decimalstill a floating point type instead of a fixed point type.
同样,数字和小数点的位置都在值中编码——这就是使decimal仍然是浮点类型而不是定点类型的原因。
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.
需要注意的重要一点是,人类习惯于以十进制形式表示非整数,并期望以十进制表示形式得到精确的结果;并非所有的十进制数都可以用二进制浮点精确表示——例如 0.1——所以如果你使用二进制浮点值,你实际上会得到 0.1 的近似值。使用浮动小数点时,您仍然会得到近似值——例如,无法准确表示 1 除以 3 的结果。
As for what to use when:
至于什么时候使用:
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.For values which are more artefacts of nature which can't really be measured exactlyanyway,
float/doubleare 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.
对于“自然精确小数”的值,最好使用
decimal. 这通常适用于人类发明的任何概念:金融价值是最明显的例子,但也有其他的。例如,考虑给潜水员或滑冰者的分数。对于更多是无法真正准确测量的自然人工制品的值,
float/double更合适。例如,科学数据通常以这种形式表示。在这里,原始值一开始不会是“十进制准确度”,因此对于预期结果来说,保持“十进制准确度”并不重要。浮点二进制小数点类型比十进制数要快得多。
回答by cgreeno
Precision is the main difference.
精度是主要区别。
Float- 7 digits (32 bit)
浮点数- 7 位(32 位)
Double-15-16 digits (64 bit)
双-15-16 位(64 位)
Decimal-28-29 significant digits (128 bit)
十进制-28-29 位有效数字(128 位)
Decimals have much higher precision and are usually used within financial applications that require a high degree of accuracy. Decimals are much slower (up to 20X times in some tests) than a double/float.
小数具有更高的精度,通常用于需要高度精度的金融应用程序中。Decimals 比 double/float 慢得多(在某些测试中高达 20 倍)。
Decimals and Floats/Doubles cannot be compared without a cast whereas Floats and Doubles can. Decimals also allow the encoding or trailing zeros.
Decimals 和 Floats/Doubles 不能在没有转换的情况下进行比较,而 Floats 和 Doubles 可以。小数还允许编码或尾随零。
float flt = 1F/3;
double dbl = 1D/3;
decimal dcm = 1M/3;
Console.WriteLine("float: {0} double: {1} decimal: {2}", flt, dbl, dcm);
Result :
结果 :
float: 0.3333333
double: 0.333333333333333
decimal: 0.3333333333333333333333333333
回答by Mark Jones
The Decimal structure is strictly geared to financial calculations requiring accuracy, which are relatively intolerant of rounding. Decimals are not adequate for scientific applications, however, for several reasons:
Decimal 结构严格适用于需要准确性的财务计算,这些计算相对不能容忍四舍五入。然而,由于以下几个原因,小数不足以用于科学应用:
- A certain loss of precision is acceptable in many scientific calculations because of the practical limits of the physical problem or artifact being measured. Loss of precision is not acceptable in finance.
- Decimal is much (much) slower than float and double for most operations, primarily because floating point operations are done in binary, whereas Decimal stuff is done in base 10 (i.e. floats and doubles are handled by the FPU hardware, such as MMX/SSE, whereas decimals are calculated in software).
- Decimal has an unacceptably smaller value range than double, despite the fact that it supports more digits of precision. Therefore, Decimal can't be used to represent many scientific values.
- 由于被测量的物理问题或人工制品的实际限制,在许多科学计算中,一定程度的精度损失是可以接受的。在金融领域,精度损失是不可接受的。
- 对于大多数操作而言,Decimal 比 float 和 double 慢得多,主要是因为浮点运算是以二进制完成的,而 Decimal 的运算是以 10 为基数完成的(即浮点和双精度由 FPU 硬件处理,例如 MMX/SSE ,而小数是在软件中计算的)。
- 尽管 Decimal 支持更多位数的精度,但其值范围比 double 小得令人无法接受。因此,Decimal 不能用于表示许多科学值。
回答by Mark Jones
+---------+----------------+---------+----------+---------------------------------------------+
| C# | .Net Framework | Signed? | Bytes | Possible Values |
| Type | (System) type | | Occupied | |
+---------+----------------+---------+----------+---------------------------------------------+
| sbyte | System.Sbyte | Yes | 1 | -128 to 127 |
| short | System.Int16 | Yes | 2 | -32768 to 32767 |
| int | System.Int32 | Yes | 4 | -2147483648 to 2147483647 |
| long | System.Int64 | Yes | 8 | -9223372036854775808 to 9223372036854775807 |
| byte | System.Byte | No | 1 | 0 to 255 |
| ushort | System.Uint16 | No | 2 | 0 to 65535 |
| uint | System.UInt32 | No | 4 | 0 to 4294967295 |
| ulong | System.Uint64 | No | 8 | 0 to 18446744073709551615 |
| float | System.Single | Yes | 4 | Approximately ±1.5 x 10-45 to ±3.4 x 1038 |
| | | | | with 7 significant figures |
| double | System.Double | Yes | 8 | Approximately ±5.0 x 10-324 to ±1.7 x 10308 |
| | | | | with 15 or 16 significant figures |
| decimal | System.Decimal | Yes | 12 | Approximately ±1.0 x 10-28 to ±7.9 x 1028 |
| | | | | with 28 or 29 significant figures |
| char | System.Char | N/A | 2 | Any Unicode character (16 bit) |
| bool | System.Boolean | N/A | 1 / 2 | true or false |
+---------+----------------+---------+----------+---------------------------------------------+
回答by tomosius
I won't reiterate tons of good (and some bad) information already answered in other answers and comments, but I will answer your followup question with a tip:
我不会重复其他答案和评论中已经回答的大量好的(和一些坏的)信息,但我会用一个提示回答你的后续问题:
When would someone use one of these?
什么时候有人会使用其中之一?
Use decimal for countedvalues
对计数值使用十进制
Use float/double for measuredvalues
对测量值使用 float/double
Some examples:
一些例子:
money (do we count money or measure money?)
distance (do we count distance or measure distance? *)
scores (do we count scores or measure scores?)
钱(我们算钱还是量钱?)
距离(我们是计算距离还是测量距离?*)
分数(我们是计算分数还是衡量分数?)
We always count money and should never measure it. We usually measure distance. We often count scores.
我们总是数钱,不应该衡量它。我们通常测量距离。我们经常计算分数。
* In some cases, what I would call nominal distance, we may indeed want to 'count' distance. For example, maybe we are dealing with country signs that show distances to cities, and we know that those distances never have more than one decimal digit (xxx.x km).
* 在某些情况下,我称之为标称距离,我们可能确实想要“计算”距离。例如,也许我们正在处理显示到城市距离的国家/地区标志,并且我们知道这些距离的十进制数字永远不会超过一位(xxx.x km)。
回答by CharithJ
float7 digits of precision
float7位精度
doublehas about 15 digits of precision
double有大约 15 位精度
decimalhas about 28 digits of precision
decimal大约有 28 位精度
If you need better accuracy, use double instead of float. In modern CPUs both data types have almost the same performance. The only benifit of using float is they take up less space. Practically matters only if you have got many of them.
如果您需要更高的准确性,请使用 double 而不是 float。在现代 CPU 中,两种数据类型的性能几乎相同。使用 float 的唯一好处是它们占用的空间更少。只有当你有很多的时候才真正重要。
I found this is interesting. What Every Computer Scientist Should Know About Floating-Point Arithmetic
我发现这很有趣。每个计算机科学家都应该了解的关于浮点运算的知识
回答by GorkemHalulu
No one has mentioned that
没有人提到过
In default settings, Floats (System.Single) and doubles (System.Double) will never use overflow checking while Decimal (System.Decimal) will always use overflow checking.
在默认设置中,Floats (System.Single) 和 doubles (System.Double) 永远不会使用溢出检查,而 Decimal (System.Decimal) 将始终使用溢出检查。
I mean
我的意思是
decimal myNumber = decimal.MaxValue;
myNumber += 1;
throws OverflowException.
抛出OverflowException。
But these do not:
但这些没有:
float myNumber = float.MaxValue;
myNumber += 1;
&
&
double myNumber = double.MaxValue;
myNumber += 1;
回答by daniel
Integers, as was mentioned, are whole numbers. They can't store the point something, like .7, .42, and .007. If you need to store numbers that are not whole numbers, you need a different type of variable. You can use the double type or the float type. You set these types of variables up in exactly the same way: instead of using the word int, you type doubleor float. Like this:
如前所述,整数是整数。他们无法存储点,例如 .7、.42 和 .007。如果您需要存储非整数的数字,则需要不同类型的变量。您可以使用双精度型或浮点型。您以完全相同的方式设置这些类型的变量:而不是使用单词int,而是键入double或float。像这样:
float myFloat;
double myDouble;
(floatis short for "floating point", and just means a number with a point something on the end.)
(float“浮点数”的缩写,仅表示末尾带有点的数字。)
The difference between the two is in the size of the numbers that they can hold. For float, you can have up to 7 digits in your number. For doubles, you can have up to 16 digits. To be more precise, here's the official size:
两者之间的区别在于它们可以容纳的数字的大小。对于float,您的号码最多可以有 7 位数字。对于doubles,您最多可以有 16 位数字。更准确地说,这是官方尺寸:
float: 1.5 × 10^-45 to 3.4 × 10^38
double: 5.0 × 10^-324 to 1.7 × 10^308
floatis a 32-bit number, and doubleis a 64-bit number.
float是 32 位数字,double是 64 位数字。
Double click your new button to get at the code. Add the following three lines to your button code:
双击您的新按钮以获取代码。将以下三行添加到您的按钮代码中:
double myDouble;
myDouble = 0.007;
MessageBox.Show(myDouble.ToString());
Halt your program and return to the coding window. Change this line:
暂停您的程序并返回到编码窗口。改变这一行:
myDouble = 0.007;
myDouble = 12345678.1234567;
Run your programme and click your double button. The message box correctly displays the number. Add another number on the end, though, and C# will again round up or down. The moral is if you want accuracy, be careful of rounding!
运行您的程序并单击您的双按钮。消息框正确显示数字。但是,在末尾添加另一个数字,C# 将再次向上或向下取整。寓意是,如果您想要准确性,请小心四舍五入!
回答by xport
- Double and float can be divided by integer zero without an exception at both compilation and run time.
- Decimal cannot be divided by integer zero. Compilation will always fail if you do that.
- Double 和 float 可以被整数零整除,在编译和运行时无一例外。
- 十进制不能被整数零整除。如果你这样做,编译总是会失败。
回答by Mukesh Kumar
- float: ±1.5 x 10^-45 to ±3.4 x 10^38 (~7 significant figures
- double: ±5.0 x 10^-324 to ±1.7 x 10^308 (15-16 significant figures)
- decimal: ±1.0 x 10^-28 to ±7.9 x 10^28 (28-29 significant figures)
- 浮点数:±1.5 x 10^-45 至 ±3.4 x 10^38(~7 个有效数字
- 双倍:±5.0 x 10^-324 至 ±1.7 x 10^308(15-16 位有效数字)
- 十进制:±1.0 x 10^-28 至 ±7.9 x 10^28(28-29 位有效数字)

