Does anyone know of a free-licence PHP code that would convert numbers to words in spanish?
It's needed for my work for generating bills so it needs to be accurate.
My knowledge of spanish is practically non-existent, so it would probably be hard to write it myself; I don't know anything about spanish grammar.
Edit: I've written my own version of this, for now it works for only 3 digit numbers (on both sides of the decimal symbol), but it's a good start. If I ever get it big (5 languages planned atm), I'll probably share it on github. Don't bet on it though.
You may use PHP Intl extension to do that.
if (version_compare(PHP_VERSION, '5.3.0', '<')
|| !class_exists('NumberFormatter')) {
exit('You need PHP 5.3 or above, and php_intl extension');
}
$formatter = new \NumberFormatter('es', \NumberFormatter::SPELLOUT);
echo $formatter->format(1234567) . "\n";
Output:
un millón doscientos treinta y cuatro mil quinientos sesenta y siete
It works not only with Spanish but many other languages as well.
Is there an easy way to convert a number to a word in PHP?
From the above, you can derive the "word" from the number, and then translate it to any language you like using any of the Translate API's out there ... or your own lookups.
Edit
Another way you could employ is simply hard coding in a PHP file or a text file a big array of values:
$numTranslation = array(1 => "uno", 2 => "dos");
Then, in your code, just retrieve the echo $numTranslation[2]
if the number was 2 to print out the spanish equivalent.
Edit 2
Just to make it a bit more complete, if you ever want to support multiple languages, and not just spanish:
$numTranslation = array(
1 => array("en" => "One", "es" => "uno"),
2 => array("en" => "Two", "es" => "dos")
);
And to print it out to the end user: echo $numTranslation[2]['es'];
to get the Spanish equivalent...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With