PostgreSQL – How to Round Numbers

postgresqlpostgresql-9.4

when we use SUM on a data table gives a 1 or 2 cents of difference due to rounding in Postgres.

We are using Postgres 9.4, the field data types is numeric with 19,3
and the result have to be with two decimals.

for example:

 15.309
 10.111
  5.005

and the result must be: 30.43

the query is:

SELECT SUM(fcv_total_comprobante)::numeric(19,2) 
FROM factura_venta 
WHERE DATE(fcv_fecha_comprobante) BETWEEN '2015-09-01' AND '2015-09-30'

the result given is 30.42 (because is 30.425) and must by 30.43

which would be the best way to round a number to 2 decimal places?

Best Answer

Define the attribute/column being summed as type money or as type numeric. If defining numeric you'll need to specify the percision.

http://www.postgresql.org/docs/9.4/static/datatype-money.html#DATATYPE-MONEY-TABLE