Numeric Cast Rounds Not Truncates

Casting numeric to integer rounds half away from zero instead of truncating: 3.7::int is 4 and -3.7::int is -4, unlike trunc().

SqlData Integrity

Code

snippet
-- numeric → integer 的 ::int 转换按四舍五入 (rounds):3.7 得 4,-3.7 得 -4(远离零的半舍入)
SELECT
    3.7::int        AS rounds_up,      -- 4
    -3.7::int       AS rounds_down,    -- -4:不是截断的 -3
    3.5::int        AS half_rounds,    -- 4:半舍入远离零,不是银行家舍入
    3.2::int        AS rounds_nearest, -- 3
    trunc(3.7)::int AS truncates,      -- 3:TRUNC 才是向零截断
    floor(-3.7)::int AS floors_down;   -- -4:FLOOR 向负无穷

-- 经典口径 bug:平均值先截断再参与计算,误差悄悄累积
-- 想保留小数先转 numeric,最后一步再决定舍入方式
SELECT
    7::numeric / 2          AS exact_avg,   -- 3.5000
    (7::numeric / 2)::int   AS cast_rounds, -- 4:3.5 远离零半舍入
    round(7::numeric / 2)   AS round_fn;    -- 4:round(numeric) 同样远离零

Numeric Cast Rounds Not Truncates: inside the code

What runs here is SELECT.

Both statements work on literals, so the rounding behavior of each path is directly observable. ::int rounds half away from zero — rounds_up prints 4, half_rounds shows 3.5 becoming 4, and rounds_down prints -4 rather than the truncation result -3. The neighbors in the same statement isolate the alternatives: trunc(3.7) demonstrates the toward-zero path, and floor(-3.7) demonstrates the toward-negative-infinity path.

The second statement applies the same rule to a computed value: 7::numeric / 2 is exact division (3.5), (7::numeric / 2)::int rounds that intermediate to 4, and round_fn shows round() agreeing with the cast on the same input. Keep values in numeric through intermediate steps and cast once at the end, so a rounding decision made mid-expression cannot compound.

Key statements

SELECT
    3.7::int        AS rounds_up,      -- 4
    -3.7::int       AS rounds_down,    -- -4:不是截断的 -3
    3.5::int        AS half_rounds,    -- 4:半舍入远离零,不是银行家舍入
    3.2::int        AS rounds_nearest, -- 3
    trunc(3.7)::int AS truncates,      -- 3:TRUNC 才是向零截断
    floor(-3.7)::int AS floors_down;   -- -4:FLOOR 向负无穷
SELECT
    7::numeric / 2          AS exact_avg,   -- 3.5000
    (7::numeric / 2)::int   AS cast_rounds, -- 4:3.5 远离零半舍入
    round(7::numeric / 2)   AS round_fn;    -- 4:round(numeric) 同样远离零

Interactive Tools for This Topic