How to convert numbers to letters with php?

Question:

In php 5.1 – I would like to know if currently someone knows any function where I can convert my numbers to words, for example:

$numero = "1200";
$conversion = "mil doscientos soles";

or also:

$numero = "0.25";
$conversion = "cero , veinticinco soles";

or also:

$numero = "1000500";
$conversion = "un millon quinientos soles";

or also:

$numero = "10500.25";
$conversion = diez mil quinientos , veinticinco soles";

Answer:

I don't know if this is for an exercise or for a real problem. If it is for an exercise, I suppose that the teacher wants you to implement it by going through each digit, with its for loop, etc.

If what you need is a solution without reinventing the wheel for a real program you can use a NumberFormatter (available since PHP 5.3) to get the text in the language you need:

$formatterES = new NumberFormatter("es", NumberFormatter::SPELLOUT);
echo $formatterES->format(123.45);
$formatterDE = new NumberFormatter("de", NumberFormatter::SPELLOUT);
echo $formatterDE->format(123.45);

The output is:

ciento veintitrés coma cuatro cinco
ein­hundert­drei­und­zwanzig Komma vier fünf

EDIT: By playing around with the function you can prevent it from putting "eat four five" and putting "eat forty-five":

$formatterES = new NumberFormatter("es-ES", NumberFormatter::SPELLOUT);
$n = 123.45;
$izquierda = intval(floor($n));
$derecha = intval(($n - floor($n)) * 100);
echo $formatterES->format($izquierda) . " coma " . $formatterES->format($derecha);
// ciento veintitrés coma cuarenta y cinco

More information:

Scroll to Top