PostgreSQL - rounding floating point numbers

前端 未结 2 848
栀梦
栀梦 2021-01-12 02:08

I have a newbie question about floating point numbers in PostgreSQL 9.2.

Is there a function to round a floating point number directly, i.e. without having to conver

2条回答
  •  生来不讨喜
    2021-01-12 02:50

    Try

    SELECT round((1/3.)::numeric,4);
    

    works with any version of PostgreSQL.

    There are a lack of overloads in some PostgreSQL functions, why (???): I think "it is a lack", and below show my workaround, but see this discussion for more explanations.


    Overloading as casting strategy

    You can overload the ROUND function with,

     CREATE FUNCTION ROUND(float,int) RETURNS NUMERIC AS $$
        SELECT ROUND($1::numeric,$2);
     $$ language SQL IMMUTABLE;
    

    Now your instruction will works fine, try (after function creation)

     SELECT round(1/3.,4); -- 0.3333 numeric
    

    but it returns a type NUMERIC... To preserve the first commom-usage overload, we can return a float when a text parameter is offered,

     CREATE FUNCTION ROUND(float, text, int DEFAULT 0) 
     RETURNS FLOAT AS $$
        SELECT CASE WHEN $2='dec'
                    THEN ROUND($1::numeric,$3)::float
                    -- ... WHEN $2='hex' THEN ... WHEN $2='bin' THEN... 
                    ELSE 'NaN'::float  -- is like a error message 
                END;
     $$ language SQL IMMUTABLE;
    

    Try

     SELECT round(1/3.,'dec',4);   -- 0.3333 float!
     SELECT round(2.8+1/3.,'dec',1); -- 3.1 float!
     SELECT round(2.8+1/3.,'dec'::text); -- need to cast string? pg bug 
    

    PS: You can check the overloading by \df,

     \df round
      Schema    | Name  | Datatype of result        |    Datatype of parameters                       
     -----------+-------+---------------------------+--------------------------------
     myschema   | round | numeric                   | double precision, integer                                     
     myschema   | round | double precision          | double precision, text, integer
     pg_catalog | round | double precision          | double precision                                              
     pg_catalog | round | numeric                   | numeric                                                       
     pg_catalog | round | numeric                   | numeric, integer                                              
    

    The pg_catalog functions are the default ones, see manual of build-in math functions.

提交回复
热议问题