postgresql中的round函数实际上是如何工作的?
下面的查询展示了奇怪的行为
SQL DEMO http://rextester.com/IHQ94614
select
val
,Round(x.val::NUMERIC) as NUMERIC_Round
,Round(x.val::DOUBLE PRECISION) as DOUBLE_Round
from
generate_series(-10.5,10.5,0.5) as x(val)
When Val
取“10.5”、“6.5”、“4.5”等。回合结果不同。
Docs https://www.postgresql.org/docs/current/static/functions-math.html比如说
对于双精度:
round(dp or numeric) (same as input) round to nearest integer
对于数字:
round(v numeric, s int) numeric round to s decimal places
这并不能解释为什么“10.5”、“6.5”、“4.5”的结果不同。
我究竟做错了什么?
可能一些详细的解释可以帮助理解round函数。
这一页 https://www.postgresql.org/docs/10/static/datatype-numeric.html文档中指出了不同数据类型之间舍入的差异:
类型decimal
and numeric
是等价的。这两种类型都是 SQL 标准的一部分。
当对值进行舍入时,numeric
类型舍入远离零,而(在大多数机器上)real
and double precision
类型将关系转为最接近的偶数。例如:
SELECT x,
round(x::numeric) AS num_round,
round(x::double precision) AS dbl_round
FROM generate_series(-3.5, 3.5, 1) as x;
x | num_round | dbl_round
------+-----------+-----------
-3.5 | -4 | -4
-2.5 | -3 | -2
-1.5 | -2 | -2
-0.5 | -1 | -0
0.5 | 1 | 0
1.5 | 2 | 2
2.5 | 3 | 2
3.5 | 4 | 4
(8 rows)
pgsql-hackers 邮件列表上有一些关于这些更改的讨论here https://www.postgresql.org/message-id/flat/CAEZATCWGaeLoHdsWk7Yz4jFMFOH8f%3DcapC6SjMa0HYBK5_xu5Q%40mail.gmail.com#CAEZATCWGaeLoHdsWk7Yz4jFMFOH8f=capC6SjMa0HYBK5_xu5Q@mail.gmail.com.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)