truncate function

The trunc function truncates the value of an input expression to the specified decimal places on the right of the decimal point.

Syntax:

double trunc(n [, d ])
Semantics:
  • n, d: The arguments n and d are expressions that resolve to numbers. The value of d must be in the range of -30 <=d<=30. Any value of d exceeding the maximum absolute value of 30 is truncated to 30 or -30 respectively. If d is not an integer, it is cast to an integer value.

    For example, trunc(123.456,1.5) is considered trunc(123.456,1), and trunc(123.456,50) is treated as trunc(123.456,30).

  • return type: double.
    Depending on the values of n and d, the trunc function behaves as follows:
    • If d is a positive value, the function truncates n to d places on the right of the decimal point, that is, retains only d decimal digits to the right of the decimal point.
    • If d is greater than or equal the number of digits to the right of the decimal point in n, the value of n is returned.
    • If d is not specified or zero, the function truncates n to zero places.
    • If d is a negative value, the function truncates n to the left of the decimal point, that is, sets d digits to the left of the decimal point to zero. The right of the decimal point is also set to zero. If the number of digits in n to the left of the decimal point is less than or equal to the absolute value of d, then the function returns 0.0.
    • Returns zero if n is zero, regardless of the value of d (except when d is NULL).
    • Returns a NULL value in the following cases:
      • If either of the arguments is a NULL value
      • If either of the arguments does not resolve to a number
    • Returns n if either of the arguments resolves to a NaN or infinity.
Example:
SELECT trunc(n,d) FROM Userstocks 
Value of n Value of d Output
111.567 0 or not specified 100.00
111.567 2 100.56
111.567 3 111.567
111.567 -2 100.0
111.567 -3 0.0
-111.567 2 -100.567
-111.567 -1 -110.0