proposal: minscale, rtrim, btrim functions for numeric - Mailing list pgsql-hackers

From Pavel Stehule
Subject proposal: minscale, rtrim, btrim functions for numeric
Date
Msg-id CAFj8pRDjs-navGASeF0Wk74N36YGFJ+v=Ok9_knRa7vDc-qugg@mail.gmail.com
Whole thread Raw
Responses Re: proposal: minscale, rtrim, btrim functions for numeric  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-hackers
Hi,

four years ago Marko Tiikkaja send a patch for numeric_trim functions. This functions removed ending zeroes from numeric value. This is useful feature, but there was not any progress on this patch. I think so this feature can be interesting, so I would to revitalize this patch.


Based on this discussion I would to implement three functions - prototype implementation is in plpsql and sql - final implementation will be in C.

-- returns minimal scale when the rounding the value to this scale doesn't
-- lost any informations.
CREATE OR REPLACE FUNCTION pg_catalog.minscale(numeric)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
begin
  for i in 0..256
  loop
    if round($1, i) = $1 then
      return i;
    end if;
  end loop;
end;
$function$

-- trailing zeroes from end
-- trimming only zero for numeric type has sense
CREATE OR REPLACE FUNCTION pg_catalog.rtrim(numeric)
RETURNS numeric AS $$
  SELECT round($1, pg_catalog.minscale($1))
$$ LANGUAGE sql;

-- this is due support trim function
CREATE OR REPLACE FUNCTION pg_catalog.btrim(numeric)
RETURNS numeric AS $$
  SELECT pg_catalog.rtrim($1)
$$ LANGUAGE sql;

postgres=# select trim(10.22000);
┌───────┐
│ btrim │
╞═══════╡
│ 10.22 │
└───────┘
(1 row)

postgres=# select rtrim(10.34900);
┌────────┐
│ rtrim  │
╞════════╡
│ 10.349 │
└────────┘
(1 row)

What do you think about it?

Regards

Pavel

pgsql-hackers by date:

Previous
From: Tom Lane
Date:
Subject: int64-timestamp-dependent test vs. --disable-integer-timestamps
Next
From: Tom Lane
Date:
Subject: Re: Removing pg_pltemplate and creating "trustable" extensions