Get exact result for number division

2019-08-07 04:28发布

SELECT 9/2 gives 4

Why gives postgresql automatically rounded result?

There are some option for prevent this? (That is, I need that after division, if result is float, returns exactly and not rounded result).

UPDATE:

for example from function, I need return floating number

       CREATE OR REPLACE FUNCTION division_test (arg1 INTEGER, arg2 INTEGER,) RETURNS NUMERIC
        AS $$
            BEGIN
            RETURN arg1 / arg2;
            END;
        $$
        LANGUAGE plpgsql;

SELECT division_test (9,2)

result: 4

How to solve this problem?

2条回答
虎瘦雄心在
2楼-- · 2019-08-07 05:22

One option multiply or divide by 1.0, the result will be a decimal.

psql (9.4.5)
Type "help" for help.

tabd=# select 1 / 10;  
----------
    0 (1 row)

tabd=# select 1.0 * 1 / 10;    
------------------------
 0.10000000000000000000 (1 row)
查看更多
别忘想泡老子
3楼-- · 2019-08-07 05:23

Without having tried it, would SELECT 9.0/2.0 help you?

As an answer to the edited question:

Would changing the datatype in the argument help?

       CREATE OR REPLACE FUNCTION division_test (arg1 REAL, arg2 REAL) RETURNS REAL
        AS $$
            BEGIN
            RETURN arg1 / arg2;
            END;
        $$
        LANGUAGE plpgsql;

Or depending on your required precision, you could also use NUMERIC or another fitting numeric type.

查看更多
登录 后发表回答