Search code examples
oracle-databaseplsqlsql-function

A Function that converts a number into words PL/SQL


In my Package I'm trying to write a PL/SQL function which converts numbers into words.

My Function:

FUNCTION f_numbertoword(pn_number NUMBER) RETURN VARCHAR2 IS
  f_numbertoword VARCHAR2(34);
BEGIN
f_numbertoword := (                      <-- Here the 'Statement Ignored' error is raised
  REPLACE(
    REPLACE(
      REPLACE(
        REPLACE(
          REPLACE(
            REPLACE(
              REPLACE(
                REPLACE(
                  REPLACE(
                    REPLACE(pn_number),  <-- Here the PLS-00306 error is raised
                    '0','zero '),
                  '1','one '),
                '2','two '),
              '3','three '),
            '4','four '),
          '5','five '),
        '6','six '),
      '7','seven '),
    '8','eight '),
  '9','nine ');
RETURN f_numbertoword;
END;

Which provides me the following errors:

Error: PL/SQL: Statement ignored

Error: PLS-00306: wrong number or types of arguments in call to 'REPLACE'

I don't know how to take care of these errors or do you even suggest a even better and more esthetic function style to achieve the same result. e.g.

f_numbertoword(123);

Returns:

'one two three'

Thanks


Solution

  • The nesting of REPLACE and the parentheses is invalid. Fix it like this:

    FUNCTION f_numbertoword(pn_number NUMBER) RETURN VARCHAR2 IS
      f_numbertoword VARCHAR2(34);
    BEGIN
    f_numbertoword := REPLACE(
      REPLACE(
        REPLACE(
          REPLACE(
            REPLACE(
              REPLACE(
                REPLACE(
                  REPLACE(
                    REPLACE(
                      REPLACE(pn_number,
                        '0','zero '),
                      '1','one '),
                    '2','two '),
                  '3','three '),
                '4','four '),
              '5','five '),
            '6','six '),
          '7','seven '),
        '8','eight '),
      '9','nine ');
    RETURN f_numbertoword;
    END;