What is the difference between decimal
, float
and double
in .NET?
.NET中的十进制、浮点数和双精度数有什么区别?
When would someone use one of these?
什么时候有人会用这些东西?
17 个解决方案
#1
1945
float
and double
are floating binary point 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.
二进制数和二进制点的位置都被编码在值中。
decimal
is a floating decimal point type. In other words, they represent a number like this:
decimal是一种浮点型。换句话说,它们表示这样一个数字:
12345.65789
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.
同样,十进制数和小数点的位置都被编码在值中——这就是为什么十进制仍然是浮点类型而不是定点类型。
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 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.对于那些更具有自然属性但又无法精确测量的价值来说,浮动/双值更合适。例如,科学数据通常以这种形式表示。在这里,原始值一开始不会是“十进制精度”,因此保持“十进制精度”对预期结果并不重要。浮点二进制类型比小数要快得多。
#2
881
Precision is the main difference.
精度是主要的区别。
Float - 7 digits (32 bit)
浮点- 7位(32位)
Double-15-16 digits (64 bit)
Double-15-16数字(64位)
Decimal -28-29 significant digits (128 bit)
有效位(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.
小数具有更高的精度,通常用于需要高精确度的金融应用中。小数比双/浮点数慢得多(在某些测试中高达20倍)。
Decimals and Floats/Doubles cannot be compared without a cast whereas Floats and Doubles can. Decimals also allow the encoding or trailing zeros.
小数和浮点数不能在没有转换的情况下进行比较,而float和double可以。小数也允许编码或尾随零。
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
#3
64
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:
十进制的结构是严格地与需要精确的财务计算相结合的,这是相对不能容忍的四舍五入。但是,由于以下几个原因,小数不适用于科学应用:
- 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比float和double慢得多,这主要是因为浮点运算是二进制的,而Decimal是基于10的(例如浮点数和双精度数是由FPU硬件处理的,比如MMX/SSE,而Decimal是用软件计算的)。
- 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比double的值范围小得难以接受,尽管它支持更精确的数字。因此,不能用十进制来表示许多科学的值。
#4
54
for more information you can go to source of this picture:
要了解更多信息,你可以到这张照片的来源:
http://social.msdn.microsoft.com/forums/en us/csharpgeneral/thread/921a8ffc - 9829 - 4145 - bdc9 a96c1ec174a5
#5
39
float
7 digits of precision
浮动7位精度
double
has about 15 digits of precision
double大约有15位精度
decimal
has about 28 digits of precision
十进制有大约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.
如果你需要更好的准确性,使用双精度而不是浮动。在现代cpu中,两种数据类型的性能几乎相同。使用float的唯一好处是它们占用的空间更少。实际上,只有当你有很多的时候才重要。
I found this is interesting. What Every Computer Scientist Should Know About Floating-Point Arithmetic
我发现这很有趣。每个计算机科学家都应该了解浮点运算
#6
28
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.
在默认设置中,float (System.Single)和double (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;
#7
24
- Double and float can be divided by integer zero without an exception at both compilation and run time.
- Double和float可以被integer zero分割,在编译和运行时都没有异常。
- Decimal cannot be divided by integer zero. Compilation will always fail if you do that.
- 小数不能除以整数零。如果这样做,编译总是会失败。
#8
23
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 counted values
使用十进制计数。
Use float/double for measured values
对测量值使用浮动/双精度
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公里)。
#9
23
The Decimal, Double, and Float variable types are different in the way that they store the values. Precision is the main difference where float is a single precision (32 bit) floating point data type, double is a double precision (64 bit) floating point data type and decimal is a 128-bit floating point data type.
小数、Double和Float变量类型在存储值的方式上是不同的。精度是浮动为单精度(32位)浮点数据类型、双精度(64位)浮点数据类型和十进制为128位浮点数据类型的主要区别。
Float - 32 bit (7 digits)
浮点- 32位(7位)
Double - 64 bit (15-16 digits)
双- 64位(15-16位)
Decimal - 128 bit (28-29 significant digits)
十进制- 128位(28-29位有效数字)
The main difference is Floats and Doubles are binary floating point types and a Decimal will store the value as a floating decimal point type. So Decimals have much higher precision and are usually used within monetary (financial) or scientific calculation applications that require a high degree of accuracy. But in performance wise Decimals are slower than double and float types.
主要的区别是浮点数和双精度浮点数是二进制浮点数类型,小数将值存储为浮点小数类型。因此小数具有更高的精度,通常用于货币(金融)或科学计算中,需要很高的精度。但是在性能方面,小数要比双小数和浮点数慢。
Decimal can 100% accurately represent any number within the precision of the decimal format, whereas Float and Double, cannot accurately represent all numbers, even numbers that are within their respective formats precision.
十进制可以100%准确地表示小数格式精度中的任意数字,而浮点数和双精度数不能准确地表示所有数字,即使是在它们各自的格式精度范围内的数字。
Decimal
小数
In case of financial applications, or scientific calculations, it is better to use Decimal types because it gives you a high level of accuracy and easy to avoid rounding errors
在财务应用或科学计算的情况下,最好使用十进制类型,因为它提供了很高的准确性,并且很容易避免舍入错误
Double
双
Double Types are probably the most normally used data type for real values, except handling money.
在实际值中,Double类型可能是最常用的数据类型,除了处理金钱。
Float
浮动
It is used mostly in graphic libraries because very high demands for processing powers, also used situations that can endure rounding errors.
它主要用于图形库,因为对处理能力的要求非常高,也可以用于能够忍受舍入错误的情况。
#10
20
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 double
or float
. Like this:
如前所述,整数是整数。他们不能存储点,比如。7,。42和。007。如果需要存储非整数的数字,则需要不同类型的变量。您可以使用双类型或浮动类型。您以完全相同的方式设置这些类型的变量:您输入double或float,而不是使用int这个词。是这样的:
float myFloat;
double myDouble;
(float
is 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 double
s, you can have up to 16 digits. To be more precise, here's the official size:
两者的区别在于它们能容纳的数字的大小。对于浮点数,您的数字最多可以有7位。对于双打,最多可以有16位数字。更准确地说,这是官方的尺寸:
float: 1.5 × 10^-45 to 3.4 × 10^38
double: 5.0 × 10^-324 to 1.7 × 10^308
float
is a 32-bit number, and double
is 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#就会再次四舍五入。寓意是如果你想要准确,就要小心四舍五入!
#11
12
This has been an interesting thread for me, as today, we've just had a nasty little bug, concerning decimal
having less precision than a float
.
对于我来说,这是一个有趣的线程,就像今天,我们刚刚遇到了一个令人讨厌的小错误,关于小数的精度比浮点数小。
In our C# code, we are reading numeric values from an Excel spreadsheet, converting them into a decimal
, then sending this decimal
back to a Service to save into a SQL Server database.
在c#代码中,我们从Excel电子表格中读取数值,将它们转换为小数,然后将这个小数发送回服务,以保存到SQL Server数据库中。
Microsoft.Office.Interop.Excel.Range cell = …
object cellValue = cell.Value2;
if (cellValue != null)
{
decimal value = 0;
Decimal.TryParse(cellValue.ToString(), out value);
}
Now, for almost all of our Excel values, this worked beautifully. But for some, very small Excel values, using decimal.TryParse
lost the value completely. One such example is
现在,对于我们所有的Excel值,它工作得很好。但是对于一些很小的Excel值,用小数表示。TryParse完全丢失了值。就是一个例子
-
cellValue = 0.00006317592
cellValue = 0.00006317592
-
Decimal.TryParse(cellValue.ToString(), out value); // would return 0
Decimal.TryParse(cellValue.ToString(),价值);/ /将返回0
The solution, bizarrely, was to convert the Excel values into a double
first, and then into a decimal
:
奇怪的是,解决方案是先将Excel值转换为double,然后再转换为decimal:
Microsoft.Office.Interop.Excel.Range cell = …
object cellValue = cell.Value2;
if (cellValue != null)
{
double valueDouble = 0;
double.TryParse(cellValue.ToString(), out valueDouble);
decimal value = (decimal) valueDouble;
…
}
Even though double
has less precision than a decimal
, this actually ensured small numbers would still be recognised. For some reason, double.TryParse
was actually able to retrieve such small numbers, whereas decimal.TryParse
would set them to zero.
虽然双精度比十进制精度低,但这实际上保证了小数字仍然可以被识别。出于某种原因,翻倍。TryParse实际上可以检索到这么小的数字,而decimal。TryParse就将它们设为0。
Odd. Very odd.
奇数。非常奇怪。
#12
10
float ~ ±1.5 x 10-45 to ±3.4 x 1038 --------7 figures
double ~ ±5.0 x 10-324 to ±1.7 x 10308 ------15 or 16 figures
decimal ~ ±1.0 x 10-28 to ±7.9 x 1028 --------28 or 29 figures
浮动~±1.5 x 10-45±3.4×1038 - - - - - - - - - - 7数据双~±5.0 x 10 - 324±1.7×10308 - - - - - - 15或16数字十进制~±1.0 x 28±7.9×1028 - - - - - - - - - - 28或29人物
#13
7
For applications such as games and embedded systems where memory and performance are both critical, float is usually the numeric type of choice as it is faster and half the size of a double. Integers used to be the weapon of choice, but floating point performance has overtaken integer in modern processors. Decimal is right out!
对于内存和性能都至关重要的游戏和嵌入式系统等应用程序,float通常是数字类型的选择,因为它的速度更快,只有double的一半大小。整数曾经是选择的武器,但是浮点性能在现代处理器中已经超过了整数。十进制是正确的!
#14
6
The Decimal, Double, and Float variable types are different in the way that they store the values. Precision is the main difference where float is a single precision (32 bit) floating point data type, double is a double precision (64 bit) floating point data type and decimal is a 128-bit floating point data type.
小数、Double和Float变量类型在存储值的方式上是不同的。精度是浮动为单精度(32位)浮点数据类型、双精度(64位)浮点数据类型和十进制为128位浮点数据类型的主要区别。
Float - 32 bit (7 digits)
浮点- 32位(7位)
Double - 64 bit (15-16 digits)
双- 64位(15-16位)
Decimal - 128 bit (28-29 significant digits)
十进制- 128位(28-29位有效数字)
More about...the difference between Decimal, Float and Double
更多关于……十进制、浮点数和双精度数的区别
#15
4
The problem with all these types is that a certain imprecision subsists AND that this problem can occur with small decimal numbers like in the following example
所有这些类型的问题是存在一定的不精确,这个问题可以用小小数出现,如下面的示例所示
Dim fMean as Double = 1.18
Dim fDelta as Double = 0.08
Dim fLimit as Double = 1.1
If fMean - fDelta < fLimit Then
bLower = True
Else
bLower = False
End If
Question: Which value does bLower variable contain ?
问题:鼓风机变量包含哪些值?
Answer: On a 32 bit machine bLower contains TRUE !!!
答:一台32位机风机上含有真!!
If I replace Double by Decimal, bLower contains FALSE which is the good answer.
如果我用十进制来代替双精度,鼓风机包含假的,这是好的答案。
In double, the problem is that fMean-fDelta = 1.09999999999 that is lower that 1.1.
在double中,问题是fMean-fDelta = 1.099999999999999999999比1.1要低。
Caution: I think that same problem can certainly exists for other number because Decimal is only a double with higher precision and the precision has always a limit.
注意:我认为其他数字肯定也存在同样的问题,因为Decimal是精度更高的双精度,而且精度总是有限制的。
In fact, Double, Float and Decimal correspond to BINARY decimal in COBOL !
事实上,双、浮点和十进制在COBOL中相当于二进制十进制!
It is regrettable that other numeric types implemented in COBOL don't exist in .Net. For those that don't know COBOL, there exist in COBOL following numeric type
很遗憾,在。net中不存在COBOL实现的其他数字类型。对于那些不懂COBOL的人来说,在COBOL中有一个数字类型
BINARY or COMP like float or double or decimal
PACKED-DECIMAL or COMP-3 (2 digit in 1 byte)
ZONED-DECIMAL (1 digit in 1 byte)
#16
3
The main difference between each of these is the precision.
它们之间的主要区别是精度。
float
is a 32-bit
number, double
is a 64-bit
number and decimal
is a 128-bit
number.
float是32位数字,double是64位数字,decimal是128位数字。
#17
0
In simple words:
用简单的话说:
- The Decimal, Double, and Float variable types are different in the way that they store the values.
- 十进制、双精度和浮点变量类型在存储值的方式上是不同的。
- Precision is the main difference (Notice that this is not the single difference) where float is a single precision (32 bit) floating point data type, double is a double precision (64 bit) floating point data type and decimal is a 128-bit floating point data type.
- 精度是主要的区别(注意这不是唯一的区别),浮动是一个单精度(32位)浮点数据类型,双精度是一个双精度(64位)浮点数据类型,十进制是128位浮点数据类型。
- The summary table:
- 总结表:
/==========================================================================================
Type Bits Have up to Approximate Range
/==========================================================================================
float 32 7 digits -3.4 × 10 ^ (38) to +3.4 × 10 ^ (38)
double 64 15-16 digits ±5.0 × 10 ^ (-324) to ±1.7 × 10 ^ (308)
decimal 128 28-29 significant digits ±7.9 x 10 ^ (28) or (1 to 10 ^ (28)
/==========================================================================================
You can read more
here,
Float,
Double, and
Decimal.
#1
1945
float
and double
are floating binary point 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.
二进制数和二进制点的位置都被编码在值中。
decimal
is a floating decimal point type. In other words, they represent a number like this:
decimal是一种浮点型。换句话说,它们表示这样一个数字:
12345.65789
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.
同样,十进制数和小数点的位置都被编码在值中——这就是为什么十进制仍然是浮点类型而不是定点类型。
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 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.对于那些更具有自然属性但又无法精确测量的价值来说,浮动/双值更合适。例如,科学数据通常以这种形式表示。在这里,原始值一开始不会是“十进制精度”,因此保持“十进制精度”对预期结果并不重要。浮点二进制类型比小数要快得多。
#2
881
Precision is the main difference.
精度是主要的区别。
Float - 7 digits (32 bit)
浮点- 7位(32位)
Double-15-16 digits (64 bit)
Double-15-16数字(64位)
Decimal -28-29 significant digits (128 bit)
有效位(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.
小数具有更高的精度,通常用于需要高精确度的金融应用中。小数比双/浮点数慢得多(在某些测试中高达20倍)。
Decimals and Floats/Doubles cannot be compared without a cast whereas Floats and Doubles can. Decimals also allow the encoding or trailing zeros.
小数和浮点数不能在没有转换的情况下进行比较,而float和double可以。小数也允许编码或尾随零。
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
#3
64
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:
十进制的结构是严格地与需要精确的财务计算相结合的,这是相对不能容忍的四舍五入。但是,由于以下几个原因,小数不适用于科学应用:
- 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比float和double慢得多,这主要是因为浮点运算是二进制的,而Decimal是基于10的(例如浮点数和双精度数是由FPU硬件处理的,比如MMX/SSE,而Decimal是用软件计算的)。
- 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比double的值范围小得难以接受,尽管它支持更精确的数字。因此,不能用十进制来表示许多科学的值。
#4
54
for more information you can go to source of this picture:
要了解更多信息,你可以到这张照片的来源:
http://social.msdn.microsoft.com/forums/en us/csharpgeneral/thread/921a8ffc - 9829 - 4145 - bdc9 a96c1ec174a5
#5
39
float
7 digits of precision
浮动7位精度
double
has about 15 digits of precision
double大约有15位精度
decimal
has about 28 digits of precision
十进制有大约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.
如果你需要更好的准确性,使用双精度而不是浮动。在现代cpu中,两种数据类型的性能几乎相同。使用float的唯一好处是它们占用的空间更少。实际上,只有当你有很多的时候才重要。
I found this is interesting. What Every Computer Scientist Should Know About Floating-Point Arithmetic
我发现这很有趣。每个计算机科学家都应该了解浮点运算
#6
28
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.
在默认设置中,float (System.Single)和double (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;
#7
24
- Double and float can be divided by integer zero without an exception at both compilation and run time.
- Double和float可以被integer zero分割,在编译和运行时都没有异常。
- Decimal cannot be divided by integer zero. Compilation will always fail if you do that.
- 小数不能除以整数零。如果这样做,编译总是会失败。
#8
23
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 counted values
使用十进制计数。
Use float/double for measured values
对测量值使用浮动/双精度
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公里)。
#9
23
The Decimal, Double, and Float variable types are different in the way that they store the values. Precision is the main difference where float is a single precision (32 bit) floating point data type, double is a double precision (64 bit) floating point data type and decimal is a 128-bit floating point data type.
小数、Double和Float变量类型在存储值的方式上是不同的。精度是浮动为单精度(32位)浮点数据类型、双精度(64位)浮点数据类型和十进制为128位浮点数据类型的主要区别。
Float - 32 bit (7 digits)
浮点- 32位(7位)
Double - 64 bit (15-16 digits)
双- 64位(15-16位)
Decimal - 128 bit (28-29 significant digits)
十进制- 128位(28-29位有效数字)
The main difference is Floats and Doubles are binary floating point types and a Decimal will store the value as a floating decimal point type. So Decimals have much higher precision and are usually used within monetary (financial) or scientific calculation applications that require a high degree of accuracy. But in performance wise Decimals are slower than double and float types.
主要的区别是浮点数和双精度浮点数是二进制浮点数类型,小数将值存储为浮点小数类型。因此小数具有更高的精度,通常用于货币(金融)或科学计算中,需要很高的精度。但是在性能方面,小数要比双小数和浮点数慢。
Decimal can 100% accurately represent any number within the precision of the decimal format, whereas Float and Double, cannot accurately represent all numbers, even numbers that are within their respective formats precision.
十进制可以100%准确地表示小数格式精度中的任意数字,而浮点数和双精度数不能准确地表示所有数字,即使是在它们各自的格式精度范围内的数字。
Decimal
小数
In case of financial applications, or scientific calculations, it is better to use Decimal types because it gives you a high level of accuracy and easy to avoid rounding errors
在财务应用或科学计算的情况下,最好使用十进制类型,因为它提供了很高的准确性,并且很容易避免舍入错误
Double
双
Double Types are probably the most normally used data type for real values, except handling money.
在实际值中,Double类型可能是最常用的数据类型,除了处理金钱。
Float
浮动
It is used mostly in graphic libraries because very high demands for processing powers, also used situations that can endure rounding errors.
它主要用于图形库,因为对处理能力的要求非常高,也可以用于能够忍受舍入错误的情况。
#10
20
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 double
or float
. Like this:
如前所述,整数是整数。他们不能存储点,比如。7,。42和。007。如果需要存储非整数的数字,则需要不同类型的变量。您可以使用双类型或浮动类型。您以完全相同的方式设置这些类型的变量:您输入double或float,而不是使用int这个词。是这样的:
float myFloat;
double myDouble;
(float
is 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 double
s, you can have up to 16 digits. To be more precise, here's the official size:
两者的区别在于它们能容纳的数字的大小。对于浮点数,您的数字最多可以有7位。对于双打,最多可以有16位数字。更准确地说,这是官方的尺寸:
float: 1.5 × 10^-45 to 3.4 × 10^38
double: 5.0 × 10^-324 to 1.7 × 10^308
float
is a 32-bit number, and double
is 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#就会再次四舍五入。寓意是如果你想要准确,就要小心四舍五入!
#11
12
This has been an interesting thread for me, as today, we've just had a nasty little bug, concerning decimal
having less precision than a float
.
对于我来说,这是一个有趣的线程,就像今天,我们刚刚遇到了一个令人讨厌的小错误,关于小数的精度比浮点数小。
In our C# code, we are reading numeric values from an Excel spreadsheet, converting them into a decimal
, then sending this decimal
back to a Service to save into a SQL Server database.
在c#代码中,我们从Excel电子表格中读取数值,将它们转换为小数,然后将这个小数发送回服务,以保存到SQL Server数据库中。
Microsoft.Office.Interop.Excel.Range cell = …
object cellValue = cell.Value2;
if (cellValue != null)
{
decimal value = 0;
Decimal.TryParse(cellValue.ToString(), out value);
}
Now, for almost all of our Excel values, this worked beautifully. But for some, very small Excel values, using decimal.TryParse
lost the value completely. One such example is
现在,对于我们所有的Excel值,它工作得很好。但是对于一些很小的Excel值,用小数表示。TryParse完全丢失了值。就是一个例子
-
cellValue = 0.00006317592
cellValue = 0.00006317592
-
Decimal.TryParse(cellValue.ToString(), out value); // would return 0
Decimal.TryParse(cellValue.ToString(),价值);/ /将返回0
The solution, bizarrely, was to convert the Excel values into a double
first, and then into a decimal
:
奇怪的是,解决方案是先将Excel值转换为double,然后再转换为decimal:
Microsoft.Office.Interop.Excel.Range cell = …
object cellValue = cell.Value2;
if (cellValue != null)
{
double valueDouble = 0;
double.TryParse(cellValue.ToString(), out valueDouble);
decimal value = (decimal) valueDouble;
…
}
Even though double
has less precision than a decimal
, this actually ensured small numbers would still be recognised. For some reason, double.TryParse
was actually able to retrieve such small numbers, whereas decimal.TryParse
would set them to zero.
虽然双精度比十进制精度低,但这实际上保证了小数字仍然可以被识别。出于某种原因,翻倍。TryParse实际上可以检索到这么小的数字,而decimal。TryParse就将它们设为0。
Odd. Very odd.
奇数。非常奇怪。
#12
10
float ~ ±1.5 x 10-45 to ±3.4 x 1038 --------7 figures
double ~ ±5.0 x 10-324 to ±1.7 x 10308 ------15 or 16 figures
decimal ~ ±1.0 x 10-28 to ±7.9 x 1028 --------28 or 29 figures
浮动~±1.5 x 10-45±3.4×1038 - - - - - - - - - - 7数据双~±5.0 x 10 - 324±1.7×10308 - - - - - - 15或16数字十进制~±1.0 x 28±7.9×1028 - - - - - - - - - - 28或29人物
#13
7
For applications such as games and embedded systems where memory and performance are both critical, float is usually the numeric type of choice as it is faster and half the size of a double. Integers used to be the weapon of choice, but floating point performance has overtaken integer in modern processors. Decimal is right out!
对于内存和性能都至关重要的游戏和嵌入式系统等应用程序,float通常是数字类型的选择,因为它的速度更快,只有double的一半大小。整数曾经是选择的武器,但是浮点性能在现代处理器中已经超过了整数。十进制是正确的!
#14
6
The Decimal, Double, and Float variable types are different in the way that they store the values. Precision is the main difference where float is a single precision (32 bit) floating point data type, double is a double precision (64 bit) floating point data type and decimal is a 128-bit floating point data type.
小数、Double和Float变量类型在存储值的方式上是不同的。精度是浮动为单精度(32位)浮点数据类型、双精度(64位)浮点数据类型和十进制为128位浮点数据类型的主要区别。
Float - 32 bit (7 digits)
浮点- 32位(7位)
Double - 64 bit (15-16 digits)
双- 64位(15-16位)
Decimal - 128 bit (28-29 significant digits)
十进制- 128位(28-29位有效数字)
More about...the difference between Decimal, Float and Double
更多关于……十进制、浮点数和双精度数的区别
#15
4
The problem with all these types is that a certain imprecision subsists AND that this problem can occur with small decimal numbers like in the following example
所有这些类型的问题是存在一定的不精确,这个问题可以用小小数出现,如下面的示例所示
Dim fMean as Double = 1.18
Dim fDelta as Double = 0.08
Dim fLimit as Double = 1.1
If fMean - fDelta < fLimit Then
bLower = True
Else
bLower = False
End If
Question: Which value does bLower variable contain ?
问题:鼓风机变量包含哪些值?
Answer: On a 32 bit machine bLower contains TRUE !!!
答:一台32位机风机上含有真!!
If I replace Double by Decimal, bLower contains FALSE which is the good answer.
如果我用十进制来代替双精度,鼓风机包含假的,这是好的答案。
In double, the problem is that fMean-fDelta = 1.09999999999 that is lower that 1.1.
在double中,问题是fMean-fDelta = 1.099999999999999999999比1.1要低。
Caution: I think that same problem can certainly exists for other number because Decimal is only a double with higher precision and the precision has always a limit.
注意:我认为其他数字肯定也存在同样的问题,因为Decimal是精度更高的双精度,而且精度总是有限制的。
In fact, Double, Float and Decimal correspond to BINARY decimal in COBOL !
事实上,双、浮点和十进制在COBOL中相当于二进制十进制!
It is regrettable that other numeric types implemented in COBOL don't exist in .Net. For those that don't know COBOL, there exist in COBOL following numeric type
很遗憾,在。net中不存在COBOL实现的其他数字类型。对于那些不懂COBOL的人来说,在COBOL中有一个数字类型
BINARY or COMP like float or double or decimal
PACKED-DECIMAL or COMP-3 (2 digit in 1 byte)
ZONED-DECIMAL (1 digit in 1 byte)
#16
3
The main difference between each of these is the precision.
它们之间的主要区别是精度。
float
is a 32-bit
number, double
is a 64-bit
number and decimal
is a 128-bit
number.
float是32位数字,double是64位数字,decimal是128位数字。
#17
0
In simple words:
用简单的话说:
- The Decimal, Double, and Float variable types are different in the way that they store the values.
- 十进制、双精度和浮点变量类型在存储值的方式上是不同的。
- Precision is the main difference (Notice that this is not the single difference) where float is a single precision (32 bit) floating point data type, double is a double precision (64 bit) floating point data type and decimal is a 128-bit floating point data type.
- 精度是主要的区别(注意这不是唯一的区别),浮动是一个单精度(32位)浮点数据类型,双精度是一个双精度(64位)浮点数据类型,十进制是128位浮点数据类型。
- The summary table:
- 总结表:
/==========================================================================================
Type Bits Have up to Approximate Range
/==========================================================================================
float 32 7 digits -3.4 × 10 ^ (38) to +3.4 × 10 ^ (38)
double 64 15-16 digits ±5.0 × 10 ^ (-324) to ±1.7 × 10 ^ (308)
decimal 128 28-29 significant digits ±7.9 x 10 ^ (28) or (1 to 10 ^ (28)
/==========================================================================================
You can read more
here,
Float,
Double, and
Decimal.