How would one write a function in PostgreSQL to obtain a number in words?
Input: 123
Output: Un Deux Trois
One Two Three
Input: 123.00
Output: Un Deux Trois . Zéro Zéro
One Two Three . Zero Zero
I tried to create a function for French words but this is not it.
Create or replace FUNCTION ZeroToNine (dd_amt int)
RETURNS VARCHAR(50)
AS $$
DECLARE fr_word VARCHAR(50);
BEGIN
fr_word:='';
if dd_amt = 0 then fr_word:='Zéro';
elsif dd_amt = 1 then fr_word:='Un';
elsif dd_amt = 2 then fr_word:='Deux';
elsif dd_amt = 3 then fr_word:='Trois';
elsif dd_amt = 4 then fr_word:='Quatre';
elsif dd_amt = 5 then fr_word:='Cinq';
elsif dd_amt = 6 then fr_word:='Six';
elsif dd_amt = 7 then fr_word:='Sept';
elsif dd_amt = 8 then fr_word:='Huit';
elsif dd_amt = 9 then fr_word:='Neuf';
end if;
end if;
2
Answers
This function will do the trick, but it takes a decimal as input, like your second example. It’s using some array functions to handle the input and output:
Try the following:
See demo
Here, the result of this function for (123.00) will be
{1,2,3,.,0,0}
.Then use the
unnest
function withordinality
on the resulting array from theregexp_split_to_array
function. The use of ordinality is to get the correct order of input number digits for the next step. The output of this step will be:Now, we join this result with the subquery t to get the corresponding digit text. To group digit texts in a single text we use the
string_agg
function ordered by the order we got from the ordinality. The final result of this will be:One Two Three . Zero Zero