Get exact result for number division

谁都会走 提交于 2019-12-24 06:07:36

问题


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?


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/16963926/get-exact-result-for-number-division

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!