The goal of programming is the multiobjective optimization, we write code to automatize things that would take some time to do them manually. For many projects, you will need to convert a number to its words representation to prevent that the user writes the entire number into words (e.g the number 123456789 with words would be one hundred twenty-three million, four hundred fifty-six thousand, seven hundred eighty-nine). Yeah, that's a really long number and i know that you didn't even read the entire number, so, why would your user want to write it by himself ? Make this task easy for your users by automating it in the server side. In this article you will learn to convert numbers to its words representation using the numbers_words package in a Symfony 3 project.
Requirements
In order to convert numbers to words, we are going to use the numbers_words package of PEAR. This class you can change an integer number to simple words. This can be usefull when you need to spell a currency value e.g. on an invoice. This package provides support for more than 20 languages including English, German, Spanish, Swedish, Turkish , Russian and others. According to the last test, it can convert values of up to 14 digit numbers.
Installation
To add numbers_words
in your project as a dependency, execute the following command in a terminal:
composer require pear/numbers_words
Or modify the composer.json
file of your project, add the dependency manually and then execute composer install
:
{
"require": {
"pear/numbers_words": "^0.18.1"
}
}
After the installation you will be able to use the package in your project by importing the Numbers_Words
class.
Usage
The numbers_words class provides the static method toWords. This method expects as first parameter the integer that needs to be converted into words and as second parameter the language identifier of the language that you want e.g in English:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
// Import the class
use Numbers_Words;
class DefaultController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexAction()
{
$numberToConvert = 99999999999999;
$localeEnglish = "en_US"; // Or en_GB
$wordsFromValue = Numbers_Words::toWords($numberToConvert, $localeEnglish);
return new Response($wordsFromValue);
}
}
The response of the previous controller will be ninety-nine trillion nine hundred ninety-nine billion nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine.
Other languages
As mentioned previously, the package provides support for more than 20 languages. You will only need to provide the language code with the one you need as second parameter in the static method (for more codes, please visit the repository):
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
// Import the class
use Numbers_Words;
class DefaultController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexAction()
{
$numberToConvert = 123456789;
$supportedLanguages = array(
array("languageName" => "Bulgarian", "languageCode" => "bg"),
array("languageName" => "German", "languageCode" => "de"),
array("languageName" => "Danish", "languageCode" => "dk"),
array("languageName" => "Donald Knuth number naming system", "languageCode" => "en_100"),
// notation of numbers, where one billion is 1000000 times one million.
// 1000 times million is just 'thousand million' here. The word billiard here is not used
// because English people do not use it often, and even could not know it.
array("languageName" => "British English", "languageCode" => "en_GB"),
array("languageName" => "American English", "languageCode" => "en_US"),
array("languageName" => "Spanish (Castellano)", "languageCode" => "es"),
array("languageName" => "Spanish Argentinian", "languageCode" => "es_AR"),
array("languageName" => "French ", "languageCode" => "fr"),
array("languageName" => "French (Belgium)", "languageCode" => "fr_BE"),
array("languageName" => "Hebrew", "languageCode" => "he"),
array("languageName" => "Indonesia", "languageCode" => "id"),
array("languageName" => "Italian", "languageCode" => "it_IT"),
array("languageName" => "Lithuanian ", "languageCode" => "lt"),
array("languageName" => "Dutch ", "languageCode" => "nl"),
array("languageName" => "Polish", "languageCode" => "pl"),
array("languageName" => "Brazilian ", "languageCode" => "pt_BR"),
array("languageName" => "Romanian ", "languageCode" => "ro_RO"),
array("languageName" => "Russian ", "languageCode" => "ru"),
array("languageName" => "Turkish ", "languageCode" => "tr_TR")
);
$responseString = "";
foreach($supportedLanguages as $language){
$convertedNumber = Numbers_Words::toWords($numberToConvert, $language["languageCode"]);
$responseString .= $language["languageName"] . " : ". $convertedNumber . "<br>";
}
$response = new Response($responseString);
$response->setCharset('UTF-8');
$response->headers->remove('Cache-Control');
$response->headers->set('Content-Type', 'text/html');
return $response;
}
}
And the response will be:
Bulgarian : ÑÑо двадеÑÐµÑ Ð¸ ÑÑи милиона ÑеÑиÑиÑÑоÑин пеÑдеÑÐµÑ Ð¸ ÑеÑÑ Ñ Ð¸Ð»Ñди ÑедемÑÑоÑин оÑемдеÑÐµÑ Ð¸ девеÑ
German : einhundertdreiundzwanzig Millionen vierhundertsechsundfünfzigtausendsiebenhundertneunundachtzig
Danish : et hundrede tre og tyve millioner fire hundrede seks og halvtreds tusinde syv hundrede ni og firs
Donald Knuth number naming system : one myllion twenty-three hundred myriad forty-five myriad sixty-seven hundred eighty-nine
British English : one hundred twenty-three million four hundred fifty-six thousand seven hundred eighty-nine
American English : one hundred twenty-three million four hundred fifty-six thousand seven hundred eighty-nine
Spanish (Castellano) : ciento veintitres millones cuatrocientos cincuenta y seis mil setecientos ochenta y nueve
Spanish Argentinian : ciento veintitres millones cuatrocientos cincuenta y seis mil setecientos ochenta y nueve
French : cent vingt-trois millions quatre cent cinquante-six mille sept cent quatre-vingt-neuf
French (Belgium) : cent vingt-trois millions quatre cent cinquante-six mille sept cent quatre-vingt-neuf
Hebrew : ××× ×¢×©×¨×× ×ש×××©× ×××××× ×ר××¢-×××ת ×××ש×× ×ש××©× ××פ×× ×©××¢-×××ת ש××× ×× ×תשע×
Indonesia : seratus dua puluh tiga juta empat ratus lima puluh enam ribu tujuh ratus delapan puluh sembilan
Italian : centoventitremiloniquattrocentocinquantaseimilasettecentoottantanove
Lithuanian : šimtas dvidešimt trys milijonai keturi šimtai penkiasdešimt šeši tÅ«kstanÄiai septyni šimtai aštuoniasdešimt devyni
Dutch : eenhonderddrieentwintig-Miljoen-vierhonderdzesenvijftigDuizendzevenhonderdnegenenachttig
Polish : sto dwadzieÅcia trzy miliony czterysta piÄÄdziesiÄ t szeÅÄ tysiÄcy siedemset osiemdziesiÄ t dziewiÄÄ
Brazilian : cento e vinte e três milhões quatrocentos e cinqüenta e seis mil setecentos e oitenta e nove
Romanian : una sutÄ douÄzeci Èi trei de milioane patru sute cincizeci Èi Èase de mii Èapte sute optzeci Èi nouÄ
Russian : ÑÑо двадÑаÑÑ ÑÑи миллиона ÑеÑÑÑеÑÑа пÑÑÑдеÑÑÑ ÑеÑÑÑ ÑÑÑÑÑ ÑемÑÑÐ¾Ñ Ð²Ð¾ÑемÑдеÑÑÑ Ð´ÐµÐ²ÑÑÑ
Turkish : bir yüz yirmi üç milyon dört yüz elli altı bin yedi yüz seksen dokuz
Happy coding !