Round Trunc Floor Ceiling Negative Values
ROUND ties away from zero, TRUNC cuts toward zero, and FLOOR and CEIL head toward minus and plus infinity.
Code
-- 四个函数在负数上的方向不同:ROUND 舍入 away from zero,
-- TRUNC 截断 toward zero,FLOOR 向负无穷,CEIL 向正无穷
SELECT
ROUND(-2.5) AS round_away_from_zero, -- -3
TRUNC(-2.5) AS trunc_toward_zero, -- -2
FLOOR(-2.5) AS floor_down, -- -3
CEIL(-2.5) AS ceil_up, -- -2
ROUND(2.5) AS round_positive, -- 3
TRUNC(2.789, 2) AS truncated_2dp; -- 2.78
-- 金额场景:10.005 这类两位小数边界值,ROUND 与 TRUNC 的差异会长期累积
WITH amounts AS (
SELECT * FROM (VALUES
(10.005::numeric), (10.015), (-10.005)
) AS v(amount)
)
SELECT
amount,
ROUND(amount, 2) AS rounded,
TRUNC(amount, 2) AS truncated
FROM amounts;How it works
Several statements share this file — SELECT, with amounts among the objects involved.
On negative inputs the direction is the whole story: the same -2.5 comes back as -3 from ROUND and FLOOR but as -2 from TRUNC and CEIL.
What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query.
Applying it
The amounts table is the working surface here.
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
- Which tables does the SQL touch?
- `amounts`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.