输出中的 PostgreSQL 舍入问题

PostgreSQL Rounding issue in output

我的数字查询输出无法正常使用无穷小数。该列的类型为 'numeric'。输出很好,除非小数点可以是无限的,如下所示:'1.3333333333333333'

我试过的查询

  1. CAST(sum(column) as decimal(18,2)) / 60
  1. ROUND(sum(column),2) / 60

我使用 MySQL 已经有一段时间了,这些查询在那里正常运行。我一定是遗漏了一些 Postgres 特有的东西。

输出

1
0
0
3
57.5
0.5
1.3333333333333333

你可以使用简单的转换:

postgres=# select 4/3.0;
┌────────────────────┐
│      ?column?      │
╞════════════════════╡
│ 1.3333333333333333 │
└────────────────────┘
(1 row)

postgres=# select (4/3.0)::numeric(30,2);
┌─────────┐
│ numeric │
╞═════════╡
│    1.33 │
└─────────┘
(1 row)

PostgreSQL 没有定义 round(double precision, integer)。由于@Mike Sherrill 'Cat Recall' 在评论中解释的原因,采用精度的回合版本仅适用于 numeric.

regress=> SELECT round( float8 '3.1415927', 2 );
ERROR:  function round(double precision, integer) does not exist

regress=> \df *round*
                           List of functions
   Schema   |  Name  | Result data type | Argument data types |  Type  
------------+--------+------------------+---------------------+--------
 pg_catalog | dround | double precision | double precision    | normal
 pg_catalog | round  | double precision | double precision    | normal
 pg_catalog | round  | numeric          | numeric             | normal
 pg_catalog | round  | numeric          | numeric, integer    | normal
(4 rows)

regress=> SELECT round( CAST(float8 '3.1415927' as numeric), 2);
 round 
-------
  3.14
(1 row)

(在上面,注意 float8 只是 double precision 的 shorthand 别名。您可以看到 PostgreSQL 在输出中扩展了它)。

您必须将要四舍五入的值转换为 numeric 才能使用 round 的双参数形式。只需为 shorthand 演员附加 ::numeric,例如 round(val::numeric,2).