SoFunction
Updated on 2025-04-08

Psql division retains decimals, implements upward rounding and downward rounding operations

In psql, the result obtained by using 1/4 is 0 because /it is an integer, but in some scenarios we need to keep decimals, and in some scenarios we need to round up or round.

Today I will summarize the method of retaining decimals by psql

The method I used is type conversion, similar to int/int in c, and float/int is float.

select round(1::numeric/4::numeric,2)

Convert the divisor to the numeric type and keep two decimal places. You can get 0.25

In recent use, I used cast conversion, as follows:

MAX(ceil(round( cast ( infos.qty31days as numeric )/ cast( 31 as numeric),2))) AS qty1days 

ceil is rounded upwards, both 1.4 and 1.6 are 2

Of course there is also the floor() function, that is, rounding, 1.4 is 1, then 1.6 is 2

Use these temporarily, and then learn new ones and continue to update them.

Supplement: Postgresql method to preserve decimal places

Still need to pass the cast function cast A as B

It can be used for type conversion or to determine the number of decimal places

-- # dom AverageSELECT cast(AVG(CAST(dom AS FLOAT)) AS decimal(10,2))
-- as decimal(15,2)
FROM estate_expect_deal_price_params_data_test 
where "provinceCode"='ON'
AND "createdDate" =date(now())

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.