数字、浮点和十进制数据类型之间的区别是什么?在哪些情况下应该使用哪种数据类型?
对于任何类型的财务交易(例如工资领域),哪一个是首选的,为什么?
数字、浮点和十进制数据类型之间的区别是什么?在哪些情况下应该使用哪种数据类型?
对于任何类型的财务交易(例如工资领域),哪一个是首选的,为什么?
当前回答
Decimal具有固定精度,而float具有可变精度。
EDIT (failed to read entire question): Float(53) (aka real) is a double-precision (64-bit) floating point number in SQL Server. Regular Float is a single-precision (32-bit) floating point number. Double is a good combination of precision and simplicty for a lot of calculations. You can create a very high precision number with decimal -- up to 136-bit -- but you also have to be careful that you define your precision and scale correctly so that it can contain all your intermediate calculations to the necessary number of digits.
其他回答
十进制的例子
它的潜在需求是什么?
它源于这样一个事实:最终,计算机在内部以二进制格式表示数字。这不可避免地导致舍入误差。
考虑一下:
0.1 (decimal, or "base 10") = .00011001100110011... (binary, or "base 2")
上面的省略号[…意思是“无限的”。如果你仔细看,有一个无限重复的模式(='0011')
因此,在某些情况下,计算机必须四舍五入这个值。这导致了由于重复使用存储不准确的数字而产生的累积错误。
假设您想存储财务金额(可能包含小数部分的数字)。首先,显然不能使用整数(整数没有小数部分)。 从纯数学的角度来看,自然倾向于使用浮点数。但是,在计算机中,浮点数中小数点后的部分是有限的,即“尾数”。这会导致舍入误差。
为了克服这一问题,计算机提供了特定的数据类型,以限制计算机中十进制数的二进制舍入误差。这些是数据类型 绝对应该用来表示财务金额。这些数据类型通常被称为Decimal。例如,在c#中就是这样。或者在大多数数据库中使用DECIMAL。
虽然这个问题不包括MONEY数据类型,但有些人可能会想使用MONEY数据类型进行财务计算。
注意MONEY数据类型,它的精度有限。
在这个Stackoverflow问题的答案中有很多关于它的好信息:
在SQL Server中应该选择MONEY还是DECIMAL(x,y)数据类型?
Decimal具有固定精度,而float具有可变精度。
EDIT (failed to read entire question): Float(53) (aka real) is a double-precision (64-bit) floating point number in SQL Server. Regular Float is a single-precision (32-bit) floating point number. Double is a good combination of precision and simplicty for a lot of calculations. You can create a very high precision number with decimal -- up to 136-bit -- but you also have to be careful that you define your precision and scale correctly so that it can contain all your intermediate calculations to the necessary number of digits.
它们的数据类型优先级不同
Decimal和Numeric在功能上是相同的,但仍然有数据类型优先级,这在某些情况下可能是至关重要的。
SELECT SQL_VARIANT_PROPERTY(CAST(1 AS NUMERIC) + CAST(1 AS DECIMAL),'basetype')
结果数据类型是数值型,因为它具有数据类型优先级。
按优先级列出的详尽数据类型列表:
参考链接
MSDN指南:使用十进制、浮点和真实数据
The default maximum precision of numeric and decimal data types is 38. In Transact-SQL, numeric is functionally equivalent to the decimal data type. Use the decimal data type to store numbers with decimals when the data values must be stored exactly as specified. The behavior of float and real follows the IEEE 754 specification on approximate numeric data types. Because of the approximate nature of the float and real data types, do not use these data types when exact numeric behavior is required, such as in financial applications, in operations involving rounding, or in equality checks. Instead, use the integer, decimal, money, or smallmoney data types. Avoid using float or real columns in WHERE clause search conditions, especially the = and <> operators. It is best to limit float and real columns to > or < comparisons.