Rounding to significant figures in Postgres

If you want to round numbers to a specified number of significant figures, you can do this with the logarithm functions.

For example, rounding the following numbers to two digits would do the following:

10;10
15;15
105;100
109;100
997;990
105050;100000
123456;120000
193456;190000

Here is the SQL – note the “-1” needs to be off by one from how many digits you want: -1 gives you two digits.

WITH test AS (
  SELECT 10 val
  UNION ALL SELECT 15
  UNION ALL SELECT 105
  UNION ALL SELECT 109
  UNION ALL SELECT 997
  UNION ALL SELECT 105050
  UNION ALL SELECT 123456
  UNION ALL SELECT 193456
)
SELECT 
content_size,
FLOOR(val/
     (10 ^ FLOOR(log(val)-1))) * 
  (10 ^ FLOOR(log(val)-1))
FROM test

If you want to use this with pg_size_pretty you’ll also need to cast it:

WITH test AS (
  SELECT 10 val
  UNION ALL SELECT 15
  UNION ALL SELECT 105
  UNION ALL SELECT 109
  UNION ALL SELECT 997
  UNION ALL SELECT 105050
  UNION ALL SELECT 123456
  UNION ALL SELECT 193456
)
SELECT 
  content_size,
  pg_size_pretty(
    (FLOOR(content_size /
     (10 ^ FLOOR(log(val)-1))) * 
    (10 ^ FLOOR(log(val)-1)))::BIGINT)
FROM test

This would give you:

10;"10 bytes"
15;"15 bytes"
105;"100 bytes"
109;"100 bytes"
997;"990 bytes"
105050;"98 kB"
123456;"117 kB"
193456;"186 kB"