You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中除法运算结果的数据类型是什么?

PostgreSQL中round函数与除法结果数据类型解析

首先查看PostgreSQL提供的round函数重载:

\df round
                         List of functions
   Schema   | Name  | Result data type | Argument data types | Type 
------------+-------+------------------+---------------------+------
 pg_catalog | round | double precision | double precision    | func
 pg_catalog | round | numeric          | numeric             | func
 pg_catalog | round | numeric          | numeric, integer    | func

可以看到round函数有三种可用形式:

  • 单参数double precision,返回同类型结果
  • 单参数numeric,返回同类型结果
  • 双参数numeric + integer,返回numeric结果

接下来看除法运算的示例:

select 6::float/3.3 as number;

执行结果:

number       
--------------------
 1.8181818181818183
(1 row)

当尝试用带精度参数的round处理该结果时,出现错误:

select round(6::float/3.3,4) as number;

错误输出:

ERROR:  function round(double precision, integer) does not exist
LINE 1: select round(6::float/3.3,4) as number;
                ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
Time: 0.517 ms

问题解答

除法运算结果1.8181818181818183的数据类型是double precision(PostgreSQL中float是double precision的别名)。

原因在于:6::float明确指定为double precision类型,而3.3作为无后缀的小数,在PostgreSQL中默认也是double precision类型。两个同类型的数值进行除法运算,结果会保持该类型。由于PostgreSQL没有提供round(double precision, integer)这个重载函数,因此执行上述语句会报错。如果需要对该结果进行指定精度的四舍五入,需要先将结果显式转换为numeric类型,示例如下:

select round((6::float/3.3)::numeric,4) as number;

内容的提问来源于stack exchange,提问作者showkey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 18:40:04