PSQL 中 DECIMAL 和 NUMERIC 数据类型的区别

问题描述 投票:0回答:4

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
数据类型的描述。但是,我还是不明白什么是 这些数据类型的确切用途以及在何处使用它而不是其他数据类型。

非常感谢举例的回答...

postgresql rdbms sqldatatypes
4个回答
144
投票

来自手册:

类型

decimal
numeric
是等效的。这两种类型都是 SQL 标准的一部分。

至于“为什么需要使用它”,说明书上也有解释:

numeric 类型可以存储位数非常多的数字,并且能够精确地执行计算

(强调我的)。

如果您需要带小数的数字,请使用

decimal
(或
numeric
),如果您需要不带小数的数字,请使用
integer
bigint
decimal
作为列类型的典型用途是“产品价格”列或“利率”。整数类型的典型用法是:存储订购了多少产品的列(假设您无法订购“一半”产品)。

double

real
 也是可以存储十进制值的类型,但它们是 
approximate 类型。这意味着您不一定检索存储的值。详情请参阅:http://floating-point-gui.de/


60
投票
直接引用自

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

    

24
投票
它们是彼此的同义词并且功能相同。

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>.
    

0
投票
数字(或任意精度数字)Vs。实数/双精度(或浮点类型)

浮点类型的不精确性与任意精度数字类型的精确性

浮点类型是二进制浮点运算的 IEEE 标准 754 的实现。简单来说,在浮点类型中,数字在存储之前将被转换为二进制表示形式,并在检索时以相反的方式转换。这就带来了一个问题,因为要存储具有一定精度的十进制数字,您将需要大量的二进制。

例如要存储数字 10,您至少需要 4 个二进制。仅用 3 个二进制数无法真正存储大于 15 的数字。推断这个例子,你会丢失一些值。

有关精度的更多信息请参见此处:

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_math.html#496

SELECT CAST(12.5432107 AS real);


结果:12.54321098

那么这有什么影响呢?那么postgres已经记录了你需要注意的事情:

如果您需要精确的存储和计算(例如货币金额),请使用数字类型。

如果您想使用这些类型对任何重要的事情进行复杂的计算,特别是如果您依赖于边界情况(无穷大、下溢)中的某些行为,则应该仔细评估实现。

比较两个浮点值是否相等可能并不总是按预期工作

来源:

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_math.html https://www.postgresql.org/docs/current/datatype-numeric.html#DATATYPE-NUMERIC-DECIMAL

© www.soinside.com 2019 - 2024. All rights reserved.