Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trunc Function Not Specifying Decimals

I have the following in my table:

create table example (

     col_a int4,
     col_b int4,
     average_col = numeric


)

col_a = 309
col_b = 16

309 / 16 = 19.3125

When I do the following, I only get 19. Not (19.0, or 19.3125, 19.3):

TRUNC((col_a/col_b),1) = 19

What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Integers, floats, and numerics are stored differently and their math is different. This is a fundamental thing with computers, computers don’t do math like we do. Because you’re dividing integers, Postgres only does integer math. 309/16 is 19.

You need to cast at least one integer to a numeric (not a float, trunc with a second argument takes a numeric) then divide.

select trunc(309::numeric/16,1)

Demonstration

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading