How to get complete float value rather than rounding/precision?

I am trying to get the float value of the following field:

|> select_merge([p], %{post_length_avg: type(p.sum_of_post_words / p.total_posts, :float)})
|> Repo.all()

Lets say,
sum_of_post_words = 424 and total_posts = 1256
post_length_avg = 424/1256 = 0.3375796178343949

But the query returns post_length_avg = 0.0

How to get the full value 0.3375796178343949 ?

Any suggestions are appreciated.

I also came across Decimal but not sure how to use it in this case.

Postgres, like Elixir, has both floating point division and integer division. In the example you show, you are asking Postgres to do integer division because both operands are integers. And the result of 424 / 1256 will therefore be 0 and casting 0 to float will be, as you saw, 0.0.

Therefore you’ll need to cast the columns sum_of_post_words and total_posts into floats before the division.

Something like (not tested):

|> select_merge([p], %{post_length_avg: fragment("sum_of_post_words::double / total_posts::double)})
|> Repo.all()
1 Like