0

I am trying to truncate value in an array of integer to 8 decimals in Postgres in a SQL SELECT statement and get back the cleaned array.

[1.030411088488374,1.0985247734044379,1.0863039797613594]
2
  • What is the result you expect? Commented Apr 15, 2019 at 13:58
  • Expected result : [1.03041108,1.09852477,1.08630397] Commented Apr 15, 2019 at 13:59

1 Answer 1

1

You need to unnest the array, truncate every element, then aggregate the elements back into an array:

select array_agg(trunc(n, 8) order by idx)
from unnest(array[1.030411088488374,1.0985247734044379,1.0863039797613594]::numeric[]) with ordinality as t(n,idx);

If you need to do that a log, consider creating a function:

create function trunc_elements(p_numbers numeric[], p_num_digits int)
  returns numeric[]
as
$$
  select array_agg(trunc(n, p_num_digits) order by idx)
  from unnest(p_numbers) with ordinality as t(n,idx);
$$
language sql;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for suggestion, WITH ordinality seems not to be recognized
@OwenS: then you are using an unsupported Postgres version. If you do not need to preserve the original order of the elements, you can just leave it out.
@OwenS: as I said: if you don't need to preserve the element order, you can just leave it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.