是否有一个与python的int函数相同的postgres?

时间:2015-10-23 09:22:35

标签: postgresql

我在postgres中需要以下行为。以下是在python控制台中完成的。

>>> int(-1.2)
-1
>>> int(1.2)
1
>>> int(0.2)
0

我可以使用postgres的floor功能,但我不能保证只有正值。

template1=# select floor(-1.2), floor(1.2), floor(0.2);
 floor | floor | floor
-------+-------+-------
    -2 |     1 |     0

出于同样的原因,我无法使用ceil。

template1=# select ceil(-1.2), ceil(1.2), ceil(0.2);
 ceil | ceil | ceil
------+------+------
   -1 |    2 |    1

我当然可以这样做一些疯狂的事情:

template1=# select cast(split_part(cast(1.2 as text), '.', 1) as integer), cast(split_part(cast(-1.2 as text), '.', 1) as integer), cast(split_part(cast(0.2 as text), '.', 1) as integer), cast(split_part(cast(-0.2 as text), '.', 1) as integer), cast(split_part(cast(1 as text), '.', 1) as integer);

 split_part | split_part | split_part | split_part | split_part
------------+------------+------------+------------+------------
          1 |         -1 |          0 |          0 |          1

但是有比这更简单的方法吗?

1 个答案:

答案 0 :(得分:1)

使用trunc()

select trunc(-1.2), trunc(1.2), trunc(0.2);

 trunc | trunc | trunc 
-------+-------+-------
    -1 |     1 |     0
(1 row)
相关问题