PostgreSQL trunc() Function
The PostgreSQL trunc() function truncates the specified number to the specified precision and returns the result.
trunc() Syntax
This is the syntax of the PostgreSQL trunc() function:
trunc(numeric_value) -> integer
or
trunc(numeric_value, scale) -> numeric
Parameters
numeric_value-
Required. The number to truncate. It can be positive, negative, or zero, and it can be an integer or a decimal.
scale-
Optional. An integer representing numeric precision. Default is
0.
Return value
The PostgreSQL trunc() function truncates the specified number to the specified precision and returns the result.
If the argument scale is a positive integer, the trunc() function truncates the fractional part of the specified number to the specified number of digits.
If the argument scale is a negative integer, the trunc() function truncates all decimal places and replaces the last |scale|-th numbers of integer part with 0.
The trunc() function will return NULL if the argument is NULL.
PostgreSQL will give an error if you supply a parameter that is not a numeric type.
trunc() Examples
The following example demonstrates how to use the trunc() function to truncate a number to an integer.
SELECT
trunc(10.11) AS "trunc(10.11)",
trunc(10.99) AS "trunc(10.99)";
trunc(10.11) | trunc(10.99)
--------------+--------------
10 | 10The following example shows how to use the trunc() function to truncate a number to 2 decimal places.
SELECT
trunc(10.1212, 2) AS "trunc(10.1212, 2)",
trunc(10.9696, 2) AS "trunc(10.9696, 2)";
trunc(10.1212, 2) | trunc(10.9696, 2)
-------------------+-------------------
10.12 | 10.96Let us see a examples with a is a negative scale argument:
SELECT
trunc(1234, -2) AS "trunc(1234, -2)",
trunc(1234.0, -2) AS "trunc(1234.0, -2)",
trunc(1234.567, -2) AS "trunc(1234.567, -2)";
trunc(1234, -2) | trunc(1234.0, -2) | trunc(1234.567, -2)
-----------------+-------------------+---------------------
1200 | 1200 | 1200