← 中文资源

简体中文版本

numeric 转 int 是四舍五入

::int 转换按远离零的半舍入:3.7 得 4、-3.7 得 -4;要截断用 trunc,保留小数先转 numeric、最后一步再舍入。

阅读英文原文

实现说明

实际执行的是 SELECT—— 是涉及的对象。

核心语句

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) 同样远离零

代码示例

-- 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) 同样远离零