In PostgreSQL, the trunc()
function truncates a number.
More specifically, it truncates the number either toward zero, or to a specific number of decimal places.
Syntax
The trunc()
function can be used in either of the following ways:
trunc(dp or numeric)
trunc(v numeric, s int)
The first syntax truncates the number toward zero.
The second syntax truncates it to a specified number of decimal places. In this case, v
is the number, and s
is the number of decimal places.
Example of First Syntax
Here’s an example that uses the first syntax.
SELECT trunc(342.49);
Result:
342
Example of Second Syntax
Here’s an example that uses the second syntax.
SELECT trunc(342.49, 1);
Result:
342.4
Adding Fractional Seconds
Here’s an example of specifying a number of decimal places when the number doesn’t include any.
SELECT trunc(342, 3);
Result:
342.000
Negative Numbers
Here’s an example that uses a negative number.
SELECT round(-4.5);
Result:
-5
Negative Decimal Places
Here’s what happens when the second argument is a negative value.
SELECT trunc(342, -2);
Result:
300
Trunc() vs Round()
In some cases, the trunc()
function might appear to work in a similar way to round()
. But they are quite different functions.
The round()
function rounds the number. The number is rounded to the nearest integer or to the specified number of decimal places (depending on whether you give it one argument or two arguments).
The trunc()
function on the other hand simply truncates the number toward zero or to the specified decimal place. No rounding is performed.
Here’s an example to demonstrate the difference.
SELECT
round(342.49, 1),
trunc(342.49, 1);
Result:
round | trunc -------+------- 342.5 | 342.4