Amit
Amit

Reputation: 21

PostgreSQL 10.1 incorrect division output

Postgres is giving the wrong result for division when the denominator is greater than the numerator.

select 2/4 gives 0, select 4/2 works correct.

But select 2/4 should actually return 0.5 but it is returning 0 as integer

Upvotes: 1

Views: 954

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269753

Postgres does integer division on integers. Ironically, it does not do integer averages on avg(), but that is a different matter.

One solution is simply converting one of the value to numeric:

select  2/4, 2::numeric/4

Postgres will add decimal places for numerics.

Upvotes: 3

The Impaler
The Impaler

Reputation: 48770

Try a floating point division, as in:

select 2.0 / 4 -- shows 0.5

Or:

select 1.0 * 2 / 4 -- shows 0.5

Upvotes: 0

Related Questions