round Div Mod Sign Edge Behaviors
round(numeric) rounds half away from zero while round(double) rounds half to even; div truncates and mod follows the dividend's sign.
Code
WITH probes AS (
SELECT * FROM (VALUES
(2.5::numeric, 2.5::double precision),
(1.5::numeric, 1.5::double precision),
(0.5::numeric, 0.5::double precision)
) AS t(n, d)
)
SELECT
n,
d,
-- round(numeric) rounds half away from zero: 2.5 -> 3, 0.5 -> 1
round(n) AS round_numeric,
-- double precision rounds half to even per IEEE 754: 2.5 -> 2, 0.5 -> 0
round(d) AS round_double,
-- where floor and ceil split on the half values
floor(n) AS floored,
ceil(n) AS ceiling
FROM probes;
SELECT
div(-7, 3) AS div_truncates,
mod(-7, 3) AS mod_follows_dividend,
mod(7, -3) AS negative_divisor;What the demo splits
The same three half values run through both round functions. round(numeric) always moves .5 away from zero: 2.5 prints 3, 1.5 prints 2, 0.5 prints 1. round(double precision) applies IEEE 754 ties-to-even: 2.5 and 0.5 print 2 and 0, while 1.5 also lands on 2.
floor and ceil bracket each numeric value from below and above. The second SELECT demonstrates sign rules without any rounding: div(-7, 3) truncates toward zero at -2, mod(-7, 3) follows the dividend and prints -1, and mod(7, -3) keeps the dividend’s positive sign at 1.
Points to remember
- The .5 tie behavior differs by type, not by configuration.
- mod follows the dividend; div follows zero.
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Why do 2.5 and 0.5 round differently per type?
- numeric rounds ties away from zero (3 and 1); double precision rounds ties to even per IEEE 754 (2 and 0) — same input, different documented rule.
Report a problem with this exampleOpens a pre-filled issue on GitHub.