CREATE OR ALTER FUNCTION FN_NUMBER_ROUND (
    VALOR NUMERIC(18,8),
    DECIMAIS INTEGER = 8)
RETURNS NUMERIC(18,8)
AS
DECLARE VARIABLE BASE     INTEGER;
DECLARE VARIABLE ALTERADO VARCHAR(50);
BEGIN
  BASE     = DECIMAIS+1;
  ALTERADO = CAST(VALOR AS VARCHAR(50));
  IF(POSITION('.',ALTERADO) > 0)THEN
  BEGIN
     ALTERADO = REPLACE(SUBSTRING(ALTERADO FROM POSITION('.',ALTERADO) FOR 8),'.','');
     ALTERADO = SUBSTRING(ALTERADO FROM BASE FOR 1);
     IF(CHAR_LENGTH(ALTERADO) > 0)THEN
     BEGIN
        IF(CAST(ALTERADO AS INTEGER) > 5)THEN
        BEGIN
           IF(:DECIMAIS = 1) THEN BEGIN RETURN CAST(VALOR AS NUMERIC(18,1)); END
           IF(:DECIMAIS = 2) THEN BEGIN RETURN CAST(VALOR AS NUMERIC(18,2)); END
           IF(:DECIMAIS = 3) THEN BEGIN RETURN CAST(VALOR AS NUMERIC(18,3)); END
           IF(:DECIMAIS = 4) THEN BEGIN RETURN CAST(VALOR AS NUMERIC(18,4)); END
           IF(:DECIMAIS = 5) THEN BEGIN RETURN CAST(VALOR AS NUMERIC(18,5)); END
           IF(:DECIMAIS = 6) THEN BEGIN RETURN CAST(VALOR AS NUMERIC(18,6)); END
           IF(:DECIMAIS = 7) THEN BEGIN RETURN CAST(VALOR AS NUMERIC(18,7)); END
           IF(:DECIMAIS = 8) THEN BEGIN RETURN CAST(VALOR AS NUMERIC(18,8)); END
        END
        IF(CAST(ALTERADO AS INTEGER) <= 5) THEN
        BEGIN
            IF(:DECIMAIS = 1) THEN BEGIN RETURN CAST(TRUNC(VALOR,1) AS NUMERIC(18,1)); END
            IF(:DECIMAIS = 2) THEN BEGIN RETURN CAST(TRUNC(VALOR,2) AS NUMERIC(18,2)); END
            IF(:DECIMAIS = 3) THEN BEGIN RETURN CAST(TRUNC(VALOR,3) AS NUMERIC(18,3)); END
            IF(:DECIMAIS = 4) THEN BEGIN RETURN CAST(TRUNC(VALOR,4) AS NUMERIC(18,4)); END
            IF(:DECIMAIS = 5) THEN BEGIN RETURN CAST(TRUNC(VALOR,5) AS NUMERIC(18,5)); END
            IF(:DECIMAIS = 6) THEN BEGIN RETURN CAST(TRUNC(VALOR,6) AS NUMERIC(18,6)); END
            IF(:DECIMAIS = 7) THEN BEGIN RETURN CAST(TRUNC(VALOR,7) AS NUMERIC(18,7)); END
            IF(:DECIMAIS = 8) THEN BEGIN RETURN CAST(TRUNC(VALOR,8) AS NUMERIC(18,8)); END  
        END
     END
     IF(CHAR_LENGTH(ALTERADO) = 0)THEN
     BEGIN
        IF(:DECIMAIS = 1) THEN BEGIN RETURN CAST(TRUNC(VALOR,1) AS NUMERIC(18,1)); END
        IF(:DECIMAIS = 2) THEN BEGIN RETURN CAST(TRUNC(VALOR,2) AS NUMERIC(18,2)); END
        IF(:DECIMAIS = 3) THEN BEGIN RETURN CAST(TRUNC(VALOR,3) AS NUMERIC(18,3)); END
        IF(:DECIMAIS = 4) THEN BEGIN RETURN CAST(TRUNC(VALOR,4) AS NUMERIC(18,4)); END
        IF(:DECIMAIS = 5) THEN BEGIN RETURN CAST(TRUNC(VALOR,5) AS NUMERIC(18,5)); END
        IF(:DECIMAIS = 6) THEN BEGIN RETURN CAST(TRUNC(VALOR,6) AS NUMERIC(18,6)); END
        IF(:DECIMAIS = 7) THEN BEGIN RETURN CAST(TRUNC(VALOR,7) AS NUMERIC(18,7)); END
        IF(:DECIMAIS = 8) THEN BEGIN RETURN CAST(TRUNC(VALOR,8) AS NUMERIC(18,8)); END        
     END
  END
END;