postgreSQL 中
decimal
和 numeric
数据类型有什么用。根据参考文献,以下是对这些数据类型的解释。
Decimal,numeric --> It is a user specified precision, exact and range up to 131072 digits before the decimal point and up to 16383 digits after the decimal point.
上面的语句显示了
decimal
和numeric
数据类型的描述。但是,我还是不明白什么是
这些数据类型的确切用途以及在何处使用它而不是其他数据类型。
非常感谢举例的回答...
类型
和decimal
是等效的。这两种类型都是 SQL 标准的一部分。numeric
至于“为什么需要使用它”,说明书上也有解释:
numeric 类型可以存储位数非常多的数字,并且能够精确地执行计算
(强调我的)。
如果您需要带小数的数字,请使用
decimal
(或 numeric
),如果您需要不带小数的数字,请使用 integer
或 bigint
。 decimal
作为列类型的典型用途是“产品价格”列或“利率”。整数类型的典型用法是:存储订购了多少产品的列(假设您无法订购“一半”产品)。
double
和
real
也是可以存储十进制值的类型,但它们是approximate 类型。这意味着您不一定检索存储的值。详情请参阅:http://floating-point-gui.de/
https://www.postgresql.org/message-id/[电子邮件受保护]
在 Postgres 中没有任何区别。有两个类型名称 因为 SQL 标准要求我们接受这两个名称。在快速的 查看标准,似乎唯一的区别是:
17)NUMERIC specifies the data type exact numeric, with the decimal precision and scale specified by the <precision> and <scale>. 18)DECIMAL specifies the data type exact numeric, with the decimal scale specified by the <scale> and the implementation-defined decimal precision equal to or greater than the value of the specified <precision>.
即,对于 DECIMAL,允许实现允许更多数字 比要求的小数点左边。 Postgres 没有 行使这种自由,因此这些类型之间没有区别 我们。
regards, tom lane
SQL:2003 标准说:
21) NUMERIC specifies the data type
exact numeric, with the decimal
precision and scale specified by the
<precision> and <scale>.
22) DECIMAL specifies the data type
exact numeric, with the decimal scale
specified by the <scale> and the
implementation-defined decimal
precision equal to or greater than the
value of the specified <precision>.
例如要存储数字 10,您至少需要 4 个二进制。仅用 3 个二进制数无法真正存储大于 15 的数字。推断这个例子,你会丢失一些值。
有关精度的更多信息请参见此处:
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_math.html#496
SELECT CAST(12.5432107 AS real);
如果您需要精确的存储和计算(例如货币金额),请使用数字类型。
如果您想使用这些类型对任何重要的事情进行复杂的计算,特别是如果您依赖于边界情况(无穷大、下溢)中的某些行为,则应该仔细评估实现。
比较两个浮点值是否相等可能并不总是按预期工作来源:
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_math.html https://www.postgresql.org/docs/current/datatype-numeric.html#DATATYPE-NUMERIC-DECIMAL