Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to truncate to two decimal points?

I have a pretty big query at the moment and I am missing one element... I need to cut the data to two decimal points (no rounding needed). I Googled but have had trouble adapting it to the current query.

SELECT 
    FechaDeSistema, Code, 
    CASE 
        WHEN DR_Socio = @SocioNum THEN Cantidad 
    END as Debit, 
    CASE 
        WHEN CR_Socio = @SocioNum THEN Cantidad 
    END AS Credit, 
    CASE 
        WHEN DR_Socio = @SocioNum THEN BalanceDebito 
        WHEN CR_Socio = @SocioNum THEN BalanceCredito 
    END AS Balance 
FROM 
    Ledger 
WHERE 
    (Debito_Cuenta = @Acct) OR 
    (Credito_Cuenta = @Ncct) 
ORDER BY 
    FechaDeSistema DESC

I basically need to truncate the Credit and Debit "cases" (is that how you say that?) to two decimal points. How can I pull it off? Thanks in advance!

like image 843
Lord Relix Avatar asked Jul 12 '13 15:07

Lord Relix


People also ask

How do you truncate to two decimal places?

To truncate a number to 2 decimal places, miss off all the digits after the second decimal place. To truncate a number to 3 significant figures, miss off all the digits after the first 3 significant figures (the first non-zero digit and the next two digits).

How do I reduce decimal places in SQL?

There are various methods to remove decimal values in SQL: Using ROUND() function: This function in SQL Server is used to round off a specified number to a specified decimal places. Using FLOOR() function: It returns the largest integer value that is less than or equal to a number.


2 Answers

CASTing will round. If you really want to truncate you can use ROUND with the truncate option, like this..

DECLARE @MyNum DECIMAL(19,4) = 100.1294

SELECT @MyNum 'MyNum'
, CAST(@MyNum AS DECIMAL(19,2)) 'Cast will round'
, ROUND(@MyNum,2,4) 'Round with truncate option'
, CAST(ROUND(@MyNum,2,4) AS DECIMAL(19,2)) 'Better Truncate'
like image 197
Steve D Avatar answered Oct 21 '22 08:10

Steve D


Just cast it to a lower precision decimal, this will chop off the trailing digits.

cast(yourColumnName as decimal(19,2)) as desiredColumnName

More specifically to your query code

SELECT 
    FechaDeSistema, 
    Code, 
    CASE 
        WHEN DR_Socio = @SocioNum THEN cast(Cantidad as decimal(19,2)) 
    END as Debit, 
    CASE 
        WHEN CR_Socio = @SocioNum THEN cast(Cantidad as decimal(19,2)) 
    END AS Credit, 
    CASE 
        WHEN DR_Socio = @SocioNum THEN cast(BalanceDebito as decimal(19,2)) 
        WHEN CR_Socio = @SocioNum THEN cast(BalanceCredito as decimal(19,2)) 
    END AS Balance 
FROM Ledger 
WHERE (Debito_Cuenta = @Acct) 
OR    (Credito_Cuenta = @Ncct) 
ORDER BY FechaDeSistema DESC";
like image 26
Evan L Avatar answered Oct 21 '22 06:10

Evan L