CREATE OR ALTER FUNCTION FN_CALC_TRUNC (
    VALOR1 NUMERIC(18,8),
    VALOR2 NUMERIC(18,8),
    OPERACAO VARCHAR(10) = '*',
    DECIMAIS INTEGER = 8)
RETURNS NUMERIC(18,8)
AS
declare variable calc numeric(18,8);
begin
  DECIMAIS = iif(DECIMAIS is null or DECIMAIS < 0 , 8, DECIMAIS );
  VALOR1 = coalesce(VALOR1,0);
  VALOR2 = coalesce(VALOR2,0);


  EXECUTE STATEMENT 'SELECT FIRST 1 TRUNC((cast('||:VALOR1||' as double precision) '||:OPERACAO||' cast('||:VALOR2||' as double precision)),9) FROM RDB$DATABASE' INTO CALC;

  if(DECIMAIS = 0) then RETURN cast(TRUNC(CALC,0) as numeric(18,0));
  if(DECIMAIS = 1) then RETURN cast(TRUNC(CALC,1) as numeric(18,1));
  if(DECIMAIS = 2) then RETURN cast(TRUNC(CALC,2) as numeric(18,2));
  if(DECIMAIS = 3) then RETURN cast(TRUNC(CALC,3) as numeric(18,3));
  if(DECIMAIS = 4) then RETURN cast(TRUNC(CALC,4) as numeric(18,4));
  if(DECIMAIS = 5) then RETURN cast(TRUNC(CALC,5) as numeric(18,5));
  if(DECIMAIS = 6) then RETURN cast(TRUNC(CALC,6) as numeric(18,6));
  if(DECIMAIS = 7) then RETURN cast(TRUNC(CALC,7) as numeric(18,7));
  if(DECIMAIS = 8) then RETURN cast(TRUNC(CALC,8) as numeric(18,8));

END;
				
				
