- How to Convert A Number To Words In PHP
- Saved searches
- Use saved searches to filter your results more quickly
- License
- kwn/number-to-words
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- PHP — Convert Number into Word
How to Convert A Number To Words In PHP
There comes a time when you really, really want a library to get a function/task performed for you and the results of your search on the internet does not give you what you actually want. Not in this case, am sure when you google the topic you should get a couple of interesting information, but the point i want to establish is that, being a little inquisitive to find out what is under the hood will help you know how the small small pieces join together to fulfill your needs.
The purpose of this posting is to give an insight into the PHP language by looking at variable definition, some control structures, classes and some inbuilt functions.
Naming variables in PHP is not all that different from other programming languages like Java, C# and the likes, the only exception is that all variables must start with the dollar sign, $, as demonstrated in the examples below.
The data type of a variable is determined by what value it holds and as a result you are not allowed to specify a variable’s data type before using it so you won’t find something like this anywhere
This is an example of a valid PHP code snippet
mailto:'person@nowhere.com'>'person@nowhere.com'; // a string variable $year = 2010; // an integer variable /* a reference variable provided the class Company has already been defined */ $company = new Company(); ?>
Syntactically, PHP’s control structures and class definitions are just like their counterparts in the other modern languages such as Java and C#.
mailto:person@nowhere.com>person@nowhere.com */ class Company < public static $numOfInstances = 0; // Class variable private $name; // Instance variable public function __construct($name) < self::$numOfInstances++; $this->name = trim($name); > /** * Getter method for the name attribute * @return string the name of the company */ public function getName() < return $this->name; > > ?>
Another interesting thing, is the concept of associative arrays which allows you to use strings to index your arrays. eg.
value 'gh' => 'Ghana', 'sa' => 'South Africa' ); ?>
Now, lets look at some codes to convert any integer to it’s equivalent in words in English.
> class Integer < public function toText($amt) < if (is_numeric($amt)) < echo '' . number_format($amt, 0, '.', ',') . ''; $sign = $amt >0 ? '' : 'Negative '; return $sign . $this->toQuadrillions(abs($amt)); > else < throw new Exception('Only numeric values are allowed.'); >> private function toOnes($amt) < $words = array( 0 =>'Zero', 1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four', 5 => 'Five', 6 => 'Six', 7 => 'Seven', 8 => 'Eight', 9 => 'Nine' ); if ($amt >= 0 && $amt < 10) return $words[$amt]; else throw new ArrayIndexOutOfBoundsException('Array Index not defined'); >private function toTens($amt) < // handles 10 - 99 $firstDigit = intval($amt / 10); $remainder = $amt % 10; if ($firstDigit == 1) < $words = array( 0 =>'Ten', 1 => 'Eleven', 2 => 'Twelve', 3 => 'Thirteen', 4 => 'Fourteen', 5 => 'Fifteen', 6 => 'Sixteen', 7 => 'Seventeen', 8 => 'Eighteen', 9 => 'Nineteen' ); return $words[$remainder]; > else if ($firstDigit >= 2 && $firstDigit 'Twenty', 3 => 'Thirty', 4 => 'Fourty', 5 => 'Fifty', 6 => 'Sixty', 7 => 'Seventy', 8 => 'Eighty', 9 => 'Ninety' ); $rest = $remainder == 0 ? '' : $this->toOnes($remainder); return $words[$firstDigit] . ' ' . $rest; > else return $this->toOnes($amt); > private function toHundreds($amt) < $ones = intval($amt / 100); $remainder = $amt % 100; if ($ones >= 1 && $ones < 10) < $rest = $remainder == 0 ? '' : $this->toTens($remainder); return $this->toOnes($ones) . ' Hundred ' . $rest; > else return $this->toTens($amt); > private function toThousands($amt) < $hundreds = intval($amt / 1000); $remainder = $amt % 1000; if ($hundreds >= 1 && $hundreds < 1000) < $rest = $remainder == 0 ? '' : $this->toHundreds($remainder); return $this->toHundreds($hundreds) . ' Thousand ' . $rest; > else return $this->toHundreds($amt); > private function toMillions($amt) < $hundreds = intval($amt / pow(1000, 2)); $remainder = $amt % pow(1000, 2); if ($hundreds >= 1 && $hundreds < 1000) < $rest = $remainder == 0 ? '' : $this->toThousands($remainder); return $this->toHundreds($hundreds) . ' Million ' . $rest; > else return $this->toThousands($amt); > private function toBillions($amt) < $hundreds = intval($amt / pow(1000, 3)); /* Note:taking the modulos results in a negative value, but this seems to work pretty fine */ $remainder = $amt - $hundreds * pow(1000, 3); if ($hundreds >= 1 && $hundreds < 1000) < $rest = $remainder == 0 ? '' : $this->toMillions($remainder); return $this->toHundreds($hundreds) . ' Billion ' . $rest; > else return $this->toMillions($amt); > private function toTrillions($amt) < $hundreds = intval($amt / pow(1000, 4)); $remainder = $amt - $hundreds * pow(1000, 4); if ($hundreds >= 1 && $hundreds < 1000) < $rest = $remainder == 0 ? '' : $this->toBillions($remainder); return $this->toHundreds($hundreds) . ' Trillion ' . $rest; > else return $this->toBillions($amt); > private function toQuadrillions($amt) < $hundreds = intval($amt / pow(1000, 5)); $remainder = $amt - $hundreds * pow(1000, 5); if ($hundreds >= 1 && $hundreds < 1000) < $rest = $remainder == 0 ? '' : $this->toTrillions($remainder); return $this->toHundreds($hundreds) . ' Quadrillion ' . $rest; > else return $this->toTrillions($amt); > > $obj = new Integer(); echo $obj->toText(5234567); echo $obj->toText(-4191770001230128); ?>
This is the output of the above code when run
5,234,567
Five Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven
-4,191,770,001,230,128
Negative Four Quadrillion One Hundred Ninety One Trillion Seven Hundred Seventy Billion One Million Two Hundred Thirty Thousand One Hundred Twenty Eight
With this knowledge, you can attempt to write a program to convert an amount to words including the name of the currency.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Number to string standalone PHP library with i18n. Drivers for numbers and currency included.
License
kwn/number-to-words
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
PHP Number to words converter
This library converts numbers to their word representation (123 -> one hundred twenty three).
Add package to your composer.json by running:
$ composer require kwn/number-to-words
There are two types of number-to-words transformation: number and currency. In order to use a relevant transformer for specific language create an instance of NumberToWords class and call a method that creates a new instance of the desired transformer;
Create a transformer for specific language using the getNumberTransformer(‘lang’) method:
use NumberToWords\NumberToWords; // create the number to words "manager" class $numberToWords = new NumberToWords(); // build a new number transformer using the RFC 3066 language identifier $numberTransformer = $numberToWords->getNumberTransformer('en');
Transformer can be used by passing in numeric values to the toWords() method:
$numberTransformer->toWords(5120); // outputs "five thousand one hundred twenty"
It can be also used with a static method:
NumberToWords::transformNumber('en', 5120); // outputs "five thousand one hundred twenty"
Creating a currency transformer works just like a number transformer.
use NumberToWords\NumberToWords; // create the number to words "manager" class $numberToWords = new NumberToWords(); // build a new currency transformer using the RFC 3066 language identifier $currencyTransformer = $numberToWords->getCurrencyTransformer('en');
Then it can be used passing in numeric values for amount and ISO 4217 currency identifier to the toWords() method:
$currencyTransformer->toWords(5099, 'USD'); // outputs "fifty dollars ninety nine cents"
It can be also used with a static method:
NumberToWords::transformCurrency('en', 5099, 'USD'); // outputs "fifty dollars ninety nine cents"
Please keep in mind, the currency transformer accepts integers as the amount to transform. It means that if you store amounts as floats (e.g. 4.99) you need to multiply them by 100 and pass the integer (499) as an argument.
Language | Identifier | Number | Currency |
---|---|---|---|
Albanian | al | + | + |
Arabic | ar | + | + |
Azerbaijani | az | + | + |
Belgian French | fr_BE | + | — |
Brazilian Portuguese | pt_BR | + | + |
Bulgarian | bg | + | — |
Czech | cs | + | — |
Danish | dk | + | + |
Dutch | nl | + | — |
English | en | + | + |
Estonian | et | + | — |
Georgian | ka | + | + |
German | de | + | + |
French | fr | + | + |
Hungarian | hu | + | + |
Indonesian | id | + | + |
Italian | it | + | — |
Kurdish | ku | + | — |
Lithuanian | lt | + | + |
Latvian | lv | + | + |
Macedonian | mk | + | — |
Malay | ms | + | + |
Persian | fa | + | — |
Polish | pl | + | + |
Romanian | ro | + | + |
Slovak | sk | + | + |
Spanish | es | + | + |
Russian | ru | + | + |
Swedish | sv | + | — |
Turkish | tr | + | + |
Turkmen | tk | + | + |
Ukrainian | ua | + | + |
Yoruba | yo | + | + |
Many transformers were ported from the pear/Numbers_Words library. Some of them were created from scratch by contributors. Thank you!
Version 2.x — BC and major changes
Q: I found a bug. What should I do?
A: Please report an issue on GitHub. Feel free to fix it and open a pull request. I don’t know most of those languages that the library supports, so your help and contribution would be much appreciated. Thanks!
Q: My language is missing. Could it be added?
A: Unfortunately, there’s a high chance I don’t know your language. Feel free to implement the missing transformer and open a pull request. You can take a look at the existing transformers, and follow the same pattern as other languages do.
About
Number to string standalone PHP library with i18n. Drivers for numbers and currency included.
PHP — Convert Number into Word
Now let’s see example of how to convert number into word using php. i am going to learn you convert number to word in php. we will show number into word convert using php. This tutorial will give you how to convert number to word in php.
In this blog, i will show you convert number into word in php. Here i will give you full example for convert number into word using php.
In this example i am create form in one input to enter your number into convert in word using php. So let’s see the bellow example:
How to Convert Number into Words in PHP — NiceSnippets.com
$word = convertNumberToWordsForIndia($_POST[‘text-field’]);
if (!empty($word)) <
echo ‘
‘;
>
?>
function convertNumberToWordsForIndia($number) <
$words = array(
‘0’=> » ,’1’=> ‘one’ ,’2’=> ‘two’ ,’3′ => ‘three’,’4′ => ‘four’,’5′ => ‘five’,
‘6’ => ‘six’,’7′ => ‘seven’,’8′ => ‘eight’,’9′ => ‘nine’,’10’ => ‘ten’,
’11’ => ‘eleven’,’12’ => ‘twelve’,’13’ => ‘thirteen’,’14’ => ‘fouteen’,’15’ => ‘fifteen’,
’16’ => ‘sixteen’,’17’ => ‘seventeen’,’18’ => ‘eighteen’,’19’ => ‘nineteen’,’20’ => ‘twenty’,
’30’ => ‘thirty’,’40’ => ‘fourty’,’50’ => ‘fifty’,’60’ => ‘sixty’,’70’ => ‘seventy’,
’80’ => ‘eighty’,’90’ => ‘ninty’);
//First find the length of the number
$number_length = strlen($number);
//Initialize an empty array
$number_array = array(0,0,0,0,0,0,0,0,0);
$received_number_array = array();
//Store all received numbers into an array
for($i=0;$i <$number_length;$i++)<
$received_number_array[$i] = substr($number,$i,1);
>
//Populate the empty array with the numbers received — most critical operation
for($i=9-$number_length,$j=0;$i <9;$i++,$j++)<
$number_array[$i] = $received_number_array[$j];
>
$number_to_words_string = «»;
//Finding out whether it is teen ? and then multiply by 10, example 17 is seventeen, so if 1 is preceeded with 7 multiply 1 by 10 and add 7 to it.
for($i=0,$j=1;$i <9;$i++,$j++)<
//»01,23,45,6,78″
//»00,10,06,7,42″
//»00,01,90,0,00″
if($i==0 || $i==2 || $i==4 || $i==7) <
if($number_array[$j]==0 || $number_array[$i] == «1») <
$number_array[$j] = intval($number_array[$i])*10+$number_array[$j];
$number_array[$i] = 0;
>
>
>
$value = «»;
for($i=0;$i <9;$i++)<
if($i==0 || $i==2 || $i==4 || $i==7) <
$value = $number_array[$i]*10;
>
else <
$value = $number_array[$i];
>
if($value!=0) < $number_to_words_string.= $words["$value"]." "; >
if($i==1 && $value!=0) < $number_to_words_string.= "Crores "; >
if($i==3 && $value!=0) < $number_to_words_string.= "Lakhs "; >
if($i==5 && $value!=0) < $number_to_words_string.= "Thousand "; >
if($i==6 && $value!=0) < $number_to_words_string.= "Hundred & "; >
>
if($number_length>9)
return $number_to_words_string;
>
?>
✌️ Like this article? Follow me on Twitter and Facebook. You can also subscribe to RSS Feed.