CREATE OR REPLACE FUNCTION f_words_usd(p_number NUMERIC) RETURNS VARCHAR AS $$ DECLARE TYPE myArray IS ARRAY[1:13] OF VARCHAR; l_str myArray := ARRAY['', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion']; l_num VARCHAR := TRUNC(p_number)::VARCHAR; l_return TEXT := ''; l_decimal NUMERIC; l_return_decimal TEXT := ''; BEGIN -- Calculate decimal part l_decimal := p_number - TRUNC(p_number); FOR i IN 1 .. array_length(l_str, 1) LOOP EXIT WHEN l_num IS NULL OR l_num = ''; IF (SUBSTR(l_num, LENGTH(l_num) - 2, 3)::INT <> 0) THEN l_return := TO_CHAR(TO_DATE(SUBSTR(l_num, LENGTH(l_num) - 2, 3)::INT, 'J'), 'Jsp') || ' ' || l_str[i] || CASE WHEN i != 1 THEN ' ' ELSE '' END || l_return; END IF; l_num := SUBSTR(l_num, 1, LENGTH(l_num) - 3); END LOOP; IF l_return IS NOT NULL THEN l_return := l_return || ' US Dollar '; END IF; -- Handle decimal part IF l_decimal != 0 THEN l_decimal := l_decimal * 100; l_return_decimal := TO_CHAR(TO_DATE(l_decimal::INT, 'J'), 'Jsp'); l_return := l_return || ' and ' || l_return_decimal || ' Cents '; END IF; IF l_return IS NOT NULL THEN l_return := l_return || 'Only'; END IF; RETURN l_return; END; $$ LANGUAGE plpgsql;