← Back to PostgreSQL, page 1

postgresql-0003 · Easy fresher

Why does integer division return 2 for 5 / 2 in PostgreSQL, and how do you get 2.5?

Dividing two integers produces an integer, truncating toward zero. Cast one side to numeric (5::numeric / 2) or use a decimal literal (5.0 / 2) to get a fractional result. round(value, 2) works on numeric, and numeric is exact while double precision is approximate.

Full answer

Test data:

sql
CREATE TABLE scores (student text, correct int, total int);
INSERT INTO scores VALUES ('Asha', 5, 8), ('Ben', 7, 8), ('Chen', -7, 2);
sql
SELECT 5 / 2 AS int_div, 5::numeric / 2 AS num_div, 5.0 / 2 AS literal_div, -7 / 2 AS neg_div, 7 % 3 AS remainder;

Result on PostgreSQL 17:

text
 int_div |      num_div       |    literal_div     | neg_div | remainder
---------+--------------------+--------------------+---------+-----------
 2       | 2.5000000000000000 | 2.5000000000000000 | -3      | 1
(1 row)
sql
SELECT student, correct / total AS wrong_ratio, round(100.0 * correct / total, 1) AS pct FROM scores ORDER BY student;

Result:

text
 student | wrong_ratio |  pct
---------+-------------+--------
 Asha    | 0           | 62.5
 Ben     | 0           | 87.5
 Chen    | -3          | -350.0
(3 rows)
sql
SELECT 0.1::float8 + 0.2::float8 = 0.3::float8 AS float_equal, 0.1::numeric + 0.2 = 0.3 AS numeric_equal;

Output:

text
 float_equal | numeric_equal
-------------+---------------
 f           | t
(1 row)

The first row shows truncation: 5 / 2 is 2, while either numeric form gives 2.5000000000000000, because numeric division keeps extra scale. Negative results truncate toward zero, so -7 / 2 is -3. In the percentage query, writing 100.0 first turns the whole expression numeric, so the percentages are correct, while the plain ratio column is 0 for most rows. Floating-point addition misses 0.3 by a tiny amount, while numeric is exact, which is why money and percentages that must match should use numeric.

sql
CREATE TABLE scores (student text, correct int, total int);
INSERT INTO scores VALUES ('Asha', 5, 8), ('Ben', 7, 8), ('Chen', -7, 2);

SELECT 5 / 2 AS int_div, 5::numeric / 2 AS num_div, 5.0 / 2 AS literal_div, -7 / 2 AS neg_div, 7 % 3 AS remainder;

SELECT student, correct / total AS wrong_ratio, round(100.0 * correct / total, 1) AS pct FROM scores ORDER BY student;

SELECT 0.1::float8 + 0.2::float8 = 0.3::float8 AS float_equal, 0.1::numeric + 0.2 = 0.3 AS numeric_equal;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • int / int truncates
  • Cast or use a decimal literal
  • Truncation is toward zero
  • round() on numeric for display
  • numeric is exact, float is approximate

Common mistakes

  • Computing ratios with integer columns
  • Using float for money

Follow-ups

  • How does numeric scale work in division?
  • When is double precision the right choice?

Tips

  • Put the decimal first