问题
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