Php digit to word

Преобразуем число в текст на примере суммы на PHP

В одном из проектов мне потребовалось преобразовать число в текст и блуждая по страницам великой паутины. Я набрел на публикацию «PHP — получение суммы прописью» от runcore. Неожиданно во мне проснулось непреодолимое желание потренировать мозг и написать свой вариант этой полезной функции. Еще проще и и элегантнее, а главное быстрее (по моим подсчетам примерно на 40%).

Пример использования:

echo number2string(123456789); // сто двадцать три миллиона четыреста пятьдесят шесть тысяч семьсот восемьдесят девять рублей 
function number2string($number) < // обозначаем словарь в виде статической переменной функции, чтобы // при повторном использовании функции его не определять заново static $dic = array( // словарь необходимых чисел array( -2 =>'две', -1 => 'одна', 1 => 'один', 2 => 'два', 3 => 'три', 4 => 'четыре', 5 => 'пять', 6 => 'шесть', 7 => 'семь', 8 => 'восемь', 9 => 'девять', 10 => 'десять', 11 => 'одиннадцать', 12 => 'двенадцать', 13 => 'тринадцать', 14 => 'четырнадцать' , 15 => 'пятнадцать', 16 => 'шестнадцать', 17 => 'семнадцать', 18 => 'восемнадцать', 19 => 'девятнадцать', 20 => 'двадцать', 30 => 'тридцать', 40 => 'сорок', 50 => 'пятьдесят', 60 => 'шестьдесят', 70 => 'семьдесят', 80 => 'восемьдесят', 90 => 'девяносто', 100 => 'сто', 200 => 'двести', 300 => 'триста', 400 => 'четыреста', 500 => 'пятьсот', 600 => 'шестьсот', 700 => 'семьсот', 800 => 'восемьсот', 900 => 'девятьсот' ), // словарь порядков со склонениями для плюрализации array( array('рубль', 'рубля', 'рублей'), array('тысяча', 'тысячи', 'тысяч'), array('миллион', 'миллиона', 'миллионов'), array('миллиард', 'миллиарда', 'миллиардов'), array('триллион', 'триллиона', 'триллионов'), array('квадриллион', 'квадриллиона', 'квадриллионов'), // квинтиллион, секстиллион и т.д. ), // карта плюрализации array( 2, 0, 1, 1, 1, 2 ) ); // обозначаем переменную в которую будем писать сгенерированный текст $string = array(); // дополняем число нулями слева до количества цифр кратного трем, // например 1234, преобразуется в 001234 $number = str_pad($number, ceil(strlen($number)/3)*3, 0, STR_PAD_LEFT); // разбиваем число на части из 3 цифр (порядки) и инвертируем порядок частей, // т.к. мы не знаем максимальный порядок числа и будем бежать снизу // единицы, тысячи, миллионы и т.д. $parts = array_reverse(str_split($number,3)); // бежим по каждой части foreach($parts as $i=>$part) < // если часть не равна нулю, нам надо преобразовать ее в текст if($part>0) < // обозначаем переменную в которую будем писать составные числа для текущей части $digits = array(); // если число треххзначное, запоминаем количество сотен if($part>99) < $digits[] = floor($part/100)*100; >// если последние 2 цифры не равны нулю, продолжаем искать составные числа // (данный блок прокомментирую при необходимости) if($mod1=$part%100) < $mod2 = $part%10; $flag = $i==1 && $mod1!=11 && $mod1!=12 && $mod2else < $digits[] = floor($mod1/10)*10; $digits[] = $flag*$mod2; >> // берем последнее составное число, для плюрализации $last = abs(end($digits)); // преобразуем все составные числа в слова foreach($digits as $j=>$digit) < $digits[$j] = $dic[0][$digit]; >// добавляем обозначение порядка или валюту $digits[] = $dic[1][$i][(($last%=100)>4 && $last <20) ? 2 : $dic[2][min($last%10,5)]]; // объединяем составные числа в единый текст и добавляем в переменную, которую вернет функция array_unshift($string, join(' ', $digits)); >> // преобразуем переменную в текст и возвращаем из функции, ура! return join(' ', $string); > 

Повторюсь, что данный код работает быстрее всех найденных мной вариантов.

Источник

PHP: Express Number in Words [duplicate]

Is there a function that will express any given number in words? For example: If a number is 1432 , then this function will return «One thousand four hundred and thirty two».

4 Answers 4

$f = new NumberFormatter("en", NumberFormatter::SPELLOUT); echo $f->format(1432); 

That would output «one thousand four hundred thirty-two»

If you want a more verbose output use $f->setTextAttribute(NumberFormatter::DEFAULT_RULESET, «%spellout-numbering-verbose»); which will output one thousand four hundred and thirty-two

How does one get the PECL intl extension? Ubuntu PHP 7.2 server. Also is this still OK? It’s maintenance stopped in 2013 with version 3.0.0 @yitznewton

Sorry, I switched companies and stopped using PHP right after I posted that comment, so I’m afraid I don’t know anything about the current ecosystem

This «$f = new NumberFormatter(«en», NumberFormatter::SPELLOUT);» is not working for me, any tips to make this work? I’m using MS Edge for this.

You can do this in many ways I am mentioning here two ways by using The NumberFormatter class as mentioned in Martindilling answer (if you have php version 5.3.0 or higher and also PECL extension 1.0.0 or higher) or by using the following custom function.

function convertNumberToWord($num = false) < $num = str_replace(array(',', ' '), '' , trim($num)); if(! $num) < return false; >$num = (int) $num; $words = array(); $list1 = array('', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ); $list2 = array('', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', 'hundred'); $list3 = array('', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion', 'quindecillion', 'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion' ); $num_length = strlen($num); $levels = (int) (($num_length + 2) / 3); $max_length = $levels * 3; $num = substr('00' . $num, -$max_length); $num_levels = str_split($num, 3); for ($i = 0; $i < count($num_levels); $i++) < $levels--; $hundreds = (int) ($num_levels[$i] / 100); $hundreds = ($hundreds ? ' ' . $list1[$hundreds] . ' hundred' . ' ' : ''); $tens = (int) ($num_levels[$i] % 100); $singles = ''; if ( $tens < 20 ) < $tens = ($tens ? ' ' . $list1[$tens] . ' ' : '' ); >else < $tens = (int)($tens / 10); $tens = ' ' . $list2[$tens] . ' '; $singles = (int) ($num_levels[$i] % 10); $singles = ' ' . $list1[$singles] . ' '; >$words[] = $hundreds . $tens . $singles . ( ( $levels && ( int ) ( $num_levels[$i] ) ) ? ' ' . $list3[$levels] . ' ' : '' ); > //end for loop $commas = count($words); if ($commas > 1) < $commas = $commas - 1; >return implode(' ', $words); > 

Источник

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.

Источник

Читайте также:  Java multi catch exceptions
Оцените статью