Truncate decimal places arbitrarily with Postgresql

Asked

Viewed 9,012 times

2

I am making an SQL query using the function sum(). This function sums integers and fractional numbers. The problem is that it returns a double Precision with very large number. How do I limit up to two decimal places after the point?

Code

SELECT sum(comprimento * largura * qtde) as met FROM seccionada WHERE cod_secc = 'SE1'

Outcome of the consultation:

40.1699985265732

I wish the answer was:

40.16

1 answer

4


For this there is this function:

trunc( valor, [ casas_decimais ] )

and that:

round( valor, [ casas_decimais ] )

The difference between the two is that trunc does no rounding, returning 40.16 as requested in your question, and the round returns 40.17.

Applied to your code:

SELECT
   trunc( sum(comprimento * largura * qtde), 2 ) as met
FROM
   seccionada
WHERE
   cod_secc = 'SE1'

See both in action on SQL Fiddle.

  • 1

    Thanks man, the round is the best option. Thanks..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.