Do I have to cast both the numerator and the denominator to a non-integer data type to prevent integer division?
Asked
Active
Viewed 48 times
1
-
1Honestly how hard would that have been to test? `select 1/2::numeric ; 0.50000000000000000000` – Adrian Klaver Feb 06 '23 at 18:14
-
@AdrianKlaver It is *very* easy to test. All the more surprising is that some upvoted answers that I listed under **"SEE ALSO"** section have one extra cast (e.g., 2 casts, when 1 cast is enough). This extra cast is confusing and not needed. – Timur Shtatland Feb 06 '23 at 18:19
1 Answers
0
It is enough to cast one of the operands (either the numerator or the denominator) to prevent integer division, as the manual says. Casting both is not necessary:
select 2 / 4; -- 0
select 2::numeric / 4; -- 0.50000000000000000000
select 2 / 4::numeric; -- 0.50000000000000000000
select 2::numeric / 4::numeric; -- 0.50000000000000000000
SEE ALSO:
- PostgreSQL manual: Numeric Types
- PostgreSQL manual: Mathematical Functions and Operators
- PostgreSQL: When casting an integer to a non-integer type to force floating point division in PostgreSQL, which number type should I use?
These have 2 casts, while only 1 cast is needed:

Timur Shtatland
- 12,024
- 2
- 30
- 47