kev*_*kev 5 postgresql floating-point integer
尝试这个:
create table test (f float);
insert into test values (330.0);
commit;
select (8 + 330.0/60)::int; --14
select (8 + f/60)::int from test; --14
select (9 + 330.0/60)::int; --15
select (9 + f/60)::int from test; --14
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么最后一个查询返回 14 而不是 15 吗?
PostgreSQL 9.3.9 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3, 64-bit
12.04.5 LTS (GNU/Linux 3.2.0-63-virtual x86_64)
Run Code Online (Sandbox Code Playgroud)
numeric
这是舍入和类型之间的不一致float
。
regress=> select pg_typeof (9 + 330.0/60);
pg_typeof
-----------
numeric
(1 row)
regress=> select pg_typeof(9 + f/60) from test;
pg_typeof
------------------
double precision
(1 row)
regress=> select (9 + 330.0/60);
?column?
---------------------
14.5000000000000000
(1 row)
regress=> select (9 + f/60) from test;
?column?
----------
14.5
(1 row)
regress=> select (NUMERIC '14.5000000000000000')::integer;
int4
------
15
(1 row)
regress=> select (FLOAT8 '14.5000000000000000')::integer;
int4
------
14
(1 row)
Run Code Online (Sandbox Code Playgroud)
一般来说,依靠浮点的精确舍入可以在精确边界值处产生令人惊讶的结果,因为许多十进制值不能精确地用浮点表示。
如果您想要严格舍入,请考虑使用numeric
类型。您可能还会发现显式round
函数很有用。
不幸的是,据我所知,PostgreSQL 不提供可选的舍入规则或round
变体,让您选择舍入模式(银行家舍入,始终向下,偶数,奇数等),就像Java提供的那样。
归档时间: |
|
查看次数: |
1695 次 |
最近记录: |