Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql rounding to significant figures

i've tried this significant figures query from this blog (https://www.garysieling.com/blog/postgres-significant-figures-pg_size_pretty).

But it seems have fixed decimal digit on it.

SELECT FLOOR(5.4321/(10 ^ FLOOR(log(5.4321)-1))) * (10 ^ FLOOR(log(5.4321)-1))

The result from the query above is 5.4. How can i achieve query to create these results?

number | sigfig
5.4321 | 5.43
10.987 | 10.9
550.75 | 550
9850.5 | 9850
ect

Thank you for you help brothers!

like image 505
Rakaziwi Avatar asked Feb 21 '18 08:02

Rakaziwi


People also ask

How do I round to 2 decimal places in PostgreSQL?

You must cast the value to be rounded to numeric to use the two-argument form of round . Just append ::numeric for the shorthand cast, like round(val::numeric,2) . to_char will round numbers for you as part of formatting.

How do I round values in PostgreSQL?

The PostgreSQL round() function is used to return the value after rounded a number upto a specific decimal places, provided in the argument.

How do I change precision in PostgreSQL?

Try this: ALTER Table account_invoice ALTER COLUMN amount_total TYPE DECIMAL(10,5); DECIMAL(X, Y) -> X represents full length and Y represents precision of the number. Just terms are a bit confusing in PostgreSQL here: postgresql.org/docs/9.1/static/datatype-numeric.html.


1 Answers

You can use the following function to round to a number of significant digits:

CREATE OR REPLACE FUNCTION sig_digits(n anyelement, digits int) 
RETURNS numeric
AS $$
    SELECT round(n, digits - 1 - floor(log(abs(n)))::int)
$$ LANGUAGE sql IMMUTABLE STRICT;

Compared to Laurenz' answer this has the following differences:

  • the results are rounded, not floored (e.g. sig_digits(15, 1) is 20, not 10)
  • the function takes arbitrary types as first argument (like floats), not only numerics
  • it's faster, because it avoids calling log on numeric (which is slow) if possible and only calls log once
  • it returns pretty results without an unnecessary amount of trailing zeros.
like image 128
Karl Bartel Avatar answered Sep 29 '22 21:09

Karl Bartel