I'm developing a simple web application where in I need to display number a to my users in string format.
Example:
12 - One Two or Twelve
-20 - minus Two zero or minus twenty
Either way is fine. I need this to be done in PHP. Any help will be appreciated.
for the first option (spell out digits), strtr is your friend
$words = array(
'-' => 'minus ',
'1' => 'one ',
'2' => 'two ',
etc....
);
echo strtr(-123, $words);
If you want to spell out the complete number you can make use of the PEAR Numbers_Words class. This class has a toWords() method that accepts a +ve or a -ve num and returns the spelled out string representation of the number.
If you want to convert the number to string digit wise, I am not aware of any lib function. But you can code one yourself easily. user187291 gives a good way to do this in his answer.
<?php
$arr = array(
-12,
20
);
foreach($arr as $num) {
$nw = new Numbers_Words();
echo "$num = ". $nw->toWords($num)."\n";
}
?>
Output:
C:\>php a.php
-12 = minus twelve
20 = twenty
bellow I am giving you an example function. It may not be a complete one but it should get you started (I know, the question has been posted long ago. still, it may help others - )
And I am sorry for any bugs :). and lastly, it is not finished one. I just post for an example starting point.
function convertToString($number, $blankIfZero=true){
$strRep = "";
$n = intval($number);
$one2twenty = array("One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven",
"Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen");
$twenty2ninty = array("Twenty", "Thirty",
"Fourty", "Fifty", "Sixty", "Seventy", "Eighty",
"Ninety");
$hundred = "Hundred";
$thousand = "Thousand";
$million = "Million";
$billion = "Billion";
switch($n){
case 0:
if($blankIfZero == true){
$strRep= $strRep."";
break;
}else{
$strRep = $strRep."Zero";
break;
}
case $n >0 && $n <20:
$strRep = $strRep." ".$one2twenty[($n-1)];
break;
case $n >=20 && $n < 100:
$strRep = $strRep . " ". $twenty2ninty[(($n/10) - 2)];
$strRep .= convertToString($n%10);
break;
case $n >= 100 && $n <= 999:
$strRep = $strRep.$one2twenty[(($n/100)-1)]." ".$hundred. " ";
$strRep .= convertToString($n%100);
break;
case $n >= 1000 && $n < 100000:
if($n < 20000){
$strRep = $strRep.$one2twenty[(($n/1000)-1)]." ".$thousand. " ";
$strRep .= convertToString($n%1000);
break;
}else{
$strRep = $strRep . $twenty2ninty[(($n/10000) - 2)];
$strRep .= convertToString($n%10000);
break;
}
case $n >= 100000 && $n < 1000000:
$strRep .= convertToString($n/1000). " ".$thousand. " ";
$strRep .= convertToString(($n%100000)%1000);
break;
case $n >= 1000000 && $n < 10000000:
$strRep = $strRep . $one2twenty[(($n/1000000) - 1)]. " ".$million." ";
$strRep .= convertToString($n%1000000);
break;
case $n >= 10000000 && $n < 10000000000:
$strRep .= convertToString($n/1000000). " ".$million. " ";
$strRep .= convertToString(($n%1000000));
break;
}
return $strRep;
}
Building on the work that #SRC did in a previous answer, I wrote a function to convert any raw unsigned integer into English, mainly out of curiosity.
You can find the code here: a GitHub Gist by StampyCode
This code is only limited by PHP's Integer limit (64-bit):
9223372036854775807
Which is processed by this code to output:
nine quintillion, two hundred and twenty three quadrillion, three hundred and seventy two trillion, thirty six billion, eight hundred and fifty four million, seven hundred and seventy five thousand, eight hundred and seven
Code embed:
<?php
$_1to19 = [
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen",
];
$_teen = [
"twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety",
];
$_mult = [
2 => 'hundred',
3 => 'thousand',
6 => 'million',
9 => 'billion',
12 => 'trillion',
15 => 'quadrillion',
18 => 'quintillion',
21 => 'sextillion',
24 => 'septillion', // php can't count this high
27 => 'octillion',
];
$fnBase = function ($n, $x) use (&$fn, $_mult) {
return $fn($n / (10 ** $x)) . ' ' . $_mult[$x];
};
$fnOne = function ($n, $x) use (&$fn, &$fnBase) {
$y = ($n % (10 ** $x)) % (10 ** $x);
$s = $fn($y);
$sep = ($x === 2 && $s ? " and " : ($y < 100 ? ($y ? " and " : '') : ', '));
return $fnBase($n, $x) . $sep . $s;
};
$fnHundred = function ($n, $x) use (&$fn, &$fnBase) {
$y = $n % (10 ** $x);
$sep = ($y < 100 ? ($y ? ' and ' : '') : ', ');
return ', ' . $fnBase($n, $x) . $sep . $fn($y);
};
$fn = function ($n) use (&$fn, $_1to19, $_teen, $number, &$fnOne, &$fnHundred) {
switch ($n) {
case 0:
return ($number > 1 ? '' : 'zero');
case $n < 20:
return $_1to19[$n - 1];
case $n < 100:
return $_teen[($n / 10) - 2] . ' ' . $fn($n % 10);
case $n < (10 ** 3):
return $fnOne($n, 2);
};
for ($i = 4; $i < 27; ++$i) {
if ($n < (10 ** $i)) {
break;
}
}
return ($i % 3) ? $fnHundred($n, $i - ($i % 3)) : $fnOne($n, $i - 3);
};
$number = $fn((int)$number);
$number = str_replace(', , ', ', ', $number);
$number = str_replace(', ', ', ', $number);
$number = str_replace(' ', ' ', $number);
$number = ltrim($number, ', ');
return $number;
Related
I have a certificate I want to convert year to text but in the given format
convertYearToText(1994){
return "Ninteen hundred ninty six";
}
convertYearToText(2004){
return "two thousand four";
}
I have a function but it gives me One Thousand Nine Hundred Ninety-Six
numberTowords(1996)
{
$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);
}
I need the return result to be "nineteen hundred ninety-six"
please help
I took the liberty of rewriting and cleaning up your function, adding one crucial part: the conversion from
(a) One Thousand Nine Hundred Ninety Six to (b) Nineteen Hundred Ninety Six.
The function now accepts a optional second argument $year. If set to true, it will return (b), otherwise (a).
numberTowords(1996) will give (a)
numberTowords(1996,true) will give (b)
The comments in de code show what I've changed
function numberTowords($num,$year=false){
$num = str_replace(array(',', ' '), '' , trim($num));
if($num==='')return false;
$num = (int) $num;
$words = [];
$list=[
1=>['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'],
2=>['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', 'hundred'],
3=>['', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion','octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion','quindecillion', 'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion']
];
//$levels = number of parts of 3
$levels = ceil(strlen($num)/3);
if($levels===0)return false;
//$parts = parts of 3, first one left-padded with zeros
$parts = str_split(substr('00' . $num, -$levels*3), 3);
$part_count=count($parts);
//THE IMPORTANT YEAR BIT
//only if year-flag = true
//only if no more then 2 parts
//only if year < 9999
// EXAMPLE: 1986
$change = false; //<< === added flag
if($year===true && $part_count===2 && $num<9999){
//get the first digit of last part (ex: 9)
$x=substr($parts[$part_count-1],0,1);
//if first digit = 0 : skip
//else: remove from last part and add to part before
// ex: 001 => 0019 and 986 => 86
if($x!=='0'){
$parts[$part_count-2]=$parts[$part_count-2].$x;
$parts[$part_count-1]=substr($parts[$part_count-1],1);
}
}
//LOOP THE PARTS
for ($i=0; $i < $part_count; $i++) {
$w=[];
//get the (int) of part
$part_num=(int)$parts[$i];
//HUNDREDS
if($part_num >= 100){
$w[]=$list[1][(int)substr($parts[$i],0,1)];
$w[]=$list[2][10];
}
//TENS and SINGLES
$remainder=$part_num%100;
if($remainder>19){
$w[]=$list[2][floor($remainder/10)];
$w[]=$list[1][$remainder%10];
}
else{
$w[]=$list[1][$remainder];
}
// << TEST FOR FLAG
if($change===true && $i===0)
$w[]=$list[2][10];
else
$w[]=$list[3][$part_count - $i -1];
$words[]=implode(' ',$w);
} //end for loop
return implode(' ', $words);
}
Could you not just use
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo $f->format(1994);
This may also help if you don't want to use a plugin
function convertNumber($number)
{
list($integer, $fraction) = explode(".", (string) $number);
$output = "";
if ($integer{0} == "-")
{
$output = "negative ";
$integer = ltrim($integer, "-");
}
else if ($integer{0} == "+")
{
$output = "positive ";
$integer = ltrim($integer, "+");
}
if ($integer{0} == "0")
{
$output .= "zero";
}
else
{
$integer = str_pad($integer, 36, "0", STR_PAD_LEFT);
$group = rtrim(chunk_split($integer, 3, " "), " ");
$groups = explode(" ", $group);
$groups2 = array();
foreach ($groups as $g)
{
$groups2[] = convertThreeDigit($g{0}, $g{1}, $g{2});
}
for ($z = 0; $z < count($groups2); $z++)
{
if ($groups2[$z] != "")
{
$output .= $groups2[$z] . convertGroup(11 - $z) . (
$z < 11
&& !array_search('', array_slice($groups2, $z + 1, -1))
&& $groups2[11] != ''
&& $groups[11]{0} == '0'
? " and "
: ", "
);
}
}
$output = rtrim($output, ", ");
}
if ($fraction > 0)
{
$output .= " point";
for ($i = 0; $i < strlen($fraction); $i++)
{
$output .= " " . convertDigit($fraction{$i});
}
}
return $output;
}
function convertGroup($index)
{
switch ($index)
{
case 11:
return " decillion";
case 10:
return " nonillion";
case 9:
return " octillion";
case 8:
return " septillion";
case 7:
return " sextillion";
case 6:
return " quintrillion";
case 5:
return " quadrillion";
case 4:
return " trillion";
case 3:
return " billion";
case 2:
return " million";
case 1:
return " thousand";
case 0:
return "";
}
}
function convertThreeDigit($digit1, $digit2, $digit3)
{
$buffer = "";
if ($digit1 == "0" && $digit2 == "0" && $digit3 == "0")
{
return "";
}
if ($digit1 != "0")
{
$buffer .= convertDigit($digit1) . " hundred";
if ($digit2 != "0" || $digit3 != "0")
{
$buffer .= " and ";
}
}
if ($digit2 != "0")
{
$buffer .= convertTwoDigit($digit2, $digit3);
}
else if ($digit3 != "0")
{
$buffer .= convertDigit($digit3);
}
return $buffer;
}
function convertTwoDigit($digit1, $digit2)
{
if ($digit2 == "0")
{
switch ($digit1)
{
case "1":
return "ten";
case "2":
return "twenty";
case "3":
return "thirty";
case "4":
return "forty";
case "5":
return "fifty";
case "6":
return "sixty";
case "7":
return "seventy";
case "8":
return "eighty";
case "9":
return "ninety";
}
} else if ($digit1 == "1")
{
switch ($digit2)
{
case "1":
return "eleven";
case "2":
return "twelve";
case "3":
return "thirteen";
case "4":
return "fourteen";
case "5":
return "fifteen";
case "6":
return "sixteen";
case "7":
return "seventeen";
case "8":
return "eighteen";
case "9":
return "nineteen";
}
} else
{
$temp = convertDigit($digit2);
switch ($digit1)
{
case "2":
return "twenty-$temp";
case "3":
return "thirty-$temp";
case "4":
return "forty-$temp";
case "5":
return "fifty-$temp";
case "6":
return "sixty-$temp";
case "7":
return "seventy-$temp";
case "8":
return "eighty-$temp";
case "9":
return "ninety-$temp";
}
}
}
function convertDigit($digit)
{
switch ($digit)
{
case "0":
return "zero";
case "1":
return "one";
case "2":
return "two";
case "3":
return "three";
case "4":
return "four";
case "5":
return "five";
case "6":
return "six";
case "7":
return "seven";
case "8":
return "eight";
case "9":
return "nine";
}
}
I will assume you want to follow grammar and spelling rules:
It is ninety and nineteen, not ninty or ninteen.
A hyphen is required for writing out numbers between 21 and 99 that are not a multiple of 10.
Also, your function deals with numbers that are way out of the practical range of years, so I would suggest a function that specifically deals with numbers in the range 1 to 9999, taking the two points above into consideration:
function convertBelow100($pair) { // Helper function
$text = ["", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen", "twenty", "thirty",
"forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
return $pair < 20 ? $text[$pair]
: $text[18+floor($pair/10)] . ($pair%10 ? "-" . $text[$pair%10] : "");
}
function convertYearToText($year) { // Main algorithm
$century = floor($year/100);
return trim(($century%10 ? convertBelow100($century) . " hundred "
: ($year > 999 ? convertBelow100(floor($year/1000)) . " thousand " : "")
) . convertBelow100($year%100));
}
I'm new in Laravel and I'm trying to convert a number/amount to string in laravel.
Example:
Number/amount: 1,500
Converted: One Thousand, Five Hundred
How do I suppose to do that? please help thanks
Use PHP NumberFormatter class for conversion :
$digit = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo $digit->format(1000);
Output will be:
one thousand
public static function convert_number_to_words($number) {
$hyphen = '-';
$conjunction = ' and ';
$separator = ', ';
$negative = 'negative ';
$decimal = ' point ';
$dictionary = array(
0 => 'zero',
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 => 'fourteen',
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 => 'ninety',
100 => 'hundred',
1000 => 'thousand',
1000000 => 'million',
1000000000 => 'billion',
1000000000000 => 'trillion',
1000000000000000 => 'quadrillion',
1000000000000000000 => 'quintillion'
);
if (!is_numeric($number)) {
return false;
}
if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
// overflow
trigger_error(
'convert_number_to_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
E_USER_WARNING
);
return false;
}
if ($number < 0) {
return $negative . Self::convert_number_to_words(abs($number));
}
$string = $fraction = null;
if (strpos($number, '.') !== false) {
list($number, $fraction) = explode('.', $number);
}
switch (true) {
case $number < 21:
$string = $dictionary[$number];
break;
case $number < 100:
$tens = ((int) ($number / 10)) * 10;
$units = $number % 10;
$string = $dictionary[$tens];
if ($units) {
$string .= $hyphen . $dictionary[$units];
}
break;
case $number < 1000:
$hundreds = $number / 100;
$remainder = $number % 100;
$string = $dictionary[$hundreds] . ' ' . $dictionary[100];
if ($remainder) {
$string .= $conjunction . Self::convert_number_to_words($remainder);
}
break;
default:
$baseUnit = pow(1000, floor(log($number, 1000)));
$numBaseUnits = (int) ($number / $baseUnit);
$remainder = $number % $baseUnit;
$string = Self::convert_number_to_words($numBaseUnits) . ' ' . $dictionary[$baseUnit];
if ($remainder) {
$string .= $remainder < 100 ? $conjunction : $separator;
$string .= Self::convert_number_to_words($remainder);
}
break;
}
if (null !== $fraction && is_numeric($fraction)) {
$string .= $decimal;
$words = array();
foreach (str_split((string) $fraction) as $number) {
$words[] = $dictionary[$number];
}
$string .= implode(' ', $words);
}
return $string;
}
You can access the function wherever you want within the program as
Classname::convert_number_to_words(123456789.123);
// one hundred and twenty-three million, four hundred and fifty-six thousand, seven hundred and eighty-nine point one two three
<?php
/**
* English Number Converter - Collection of PHP functions to convert a number
* into English text.
*
* This exact code is licensed under CC-Wiki on Stackoverflow.
* http://creativecommons.org/licenses/by-sa/3.0/
*
* #link http://stackoverflow.com/q/277569/367456
* #question Is there an easy way to convert a number to a word in PHP?
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2007-2008 Brenton Fletcher. http://bloople.net/num2text
* You can use this freely and modify it however you want.
*/
function convertNumber($number)
{
list($integer, $fraction) = explode(".", (string) $number);
$output = "";
if ($integer{0} == "-")
{
$output = "negative ";
$integer = ltrim($integer, "-");
}
else if ($integer{0} == "+")
{
$output = "positive ";
$integer = ltrim($integer, "+");
}
if ($integer{0} == "0")
{
$output .= "zero";
}
else
{
$integer = str_pad($integer, 36, "0", STR_PAD_LEFT);
$group = rtrim(chunk_split($integer, 3, " "), " ");
$groups = explode(" ", $group);
$groups2 = array();
foreach ($groups as $g)
{
$groups2[] = convertThreeDigit($g{0}, $g{1}, $g{2});
}
for ($z = 0; $z < count($groups2); $z++)
{
if ($groups2[$z] != "")
{
$output .= $groups2[$z] . convertGroup(11 - $z) . (
$z < 11
&& !array_search('', array_slice($groups2, $z + 1, -1))
&& $groups2[11] != ''
&& $groups[11]{0} == '0'
? " and "
: ", "
);
}
}
$output = rtrim($output, ", ");
}
if ($fraction > 0)
{
$output .= " point";
for ($i = 0; $i < strlen($fraction); $i++)
{
$output .= " " . convertDigit($fraction{$i});
}
}
return $output;
}
function convertGroup($index)
{
switch ($index)
{
case 11:
return " decillion";
case 10:
return " nonillion";
case 9:
return " octillion";
case 8:
return " septillion";
case 7:
return " sextillion";
case 6:
return " quintrillion";
case 5:
return " quadrillion";
case 4:
return " trillion";
case 3:
return " billion";
case 2:
return " million";
case 1:
return " thousand";
case 0:
return "";
}
}
function convertThreeDigit($digit1, $digit2, $digit3)
{
$buffer = "";
if ($digit1 == "0" && $digit2 == "0" && $digit3 == "0")
{
return "";
}
if ($digit1 != "0")
{
$buffer .= convertDigit($digit1) . " hundred";
if ($digit2 != "0" || $digit3 != "0")
{
$buffer .= " and ";
}
}
if ($digit2 != "0")
{
$buffer .= convertTwoDigit($digit2, $digit3);
}
else if ($digit3 != "0")
{
$buffer .= convertDigit($digit3);
}
return $buffer;
}
function convertTwoDigit($digit1, $digit2)
{
if ($digit2 == "0")
{
switch ($digit1)
{
case "1":
return "ten";
case "2":
return "twenty";
case "3":
return "thirty";
case "4":
return "forty";
case "5":
return "fifty";
case "6":
return "sixty";
case "7":
return "seventy";
case "8":
return "eighty";
case "9":
return "ninety";
}
} else if ($digit1 == "1")
{
switch ($digit2)
{
case "1":
return "eleven";
case "2":
return "twelve";
case "3":
return "thirteen";
case "4":
return "fourteen";
case "5":
return "fifteen";
case "6":
return "sixteen";
case "7":
return "seventeen";
case "8":
return "eighteen";
case "9":
return "nineteen";
}
} else
{
$temp = convertDigit($digit2);
switch ($digit1)
{
case "2":
return "twenty-$temp";
case "3":
return "thirty-$temp";
case "4":
return "forty-$temp";
case "5":
return "fifty-$temp";
case "6":
return "sixty-$temp";
case "7":
return "seventy-$temp";
case "8":
return "eighty-$temp";
case "9":
return "ninety-$temp";
}
}
}
function convertDigit($digit)
{
switch ($digit)
{
case "0":
return "zero";
case "1":
return "one";
case "2":
return "two";
case "3":
return "three";
case "4":
return "four";
case "5":
return "five";
case "6":
return "six";
case "7":
return "seven";
case "8":
return "eight";
case "9":
return "nine";
}
}
Use the PHP built-in NumberFormatter class and Ensure to enable this extension in php.ini by uncommenting this line: extension=php_intl.dll
Read this , there is number class for php.
http://php.net/manual/en/class.numberformatter.php
This question already has an answer here:
Convert number into xx.xx million format? [closed]
(1 answer)
Closed 8 years ago.
I have to write a function to change a pricetype from (ex: 25400000) to 25 milion 400 thousand . I have a code but it just change when the price type is even (ex : 25000000) . Here is my code .
static public function priceFormat($number, $type ='vnd')
{
$subfix = 'vnd';
if ($type == 'vnd'){
$temp = substr($number, -6, -1);
if ($temp == '000000'){
$number = str_replace("000000", '', $number);
$subfix = 'million';
}
}
while (true) {
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
if ($replaced != $number) {
$number = $replaced;
} else {
break;
}
}
if ($type != 'vnd')
return $number.' '.$type;
return $number.' '.$subfix;
}
This code:
$number = 25400055;
$millionsRemainder = $number % 1000000;
$millions = ($number - $millionsRemainder) / 1000000;
$thousandsRemainder = $millionsRemainder % 1000;
$thousands = ($millionsRemainder - $thousandsRemainder) / 1000;
echo $millions . ' million ' . $thousands . ' thousands ' . ' and ' . $thousandsRemainder;
Should output "25 million 400 thousands and 55"
This question already has answers here:
Is there an easy way to convert a number to a word in PHP?
(14 answers)
Closed 6 years ago.
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".
Use the NumberFormatter class that are in php ;)
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo $f->format(1432);
That would output "one thousand four hundred thirty-two"
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);
}
Yes, http://www.karlrixon.co.uk/writing/convert-numbers-to-words-with-php/
However this is pretty dirty example. Please use NumberFormatter from intl (this will work from PHP 5.3)
$f = new NumberFormatter("in", NumberFormatter::SPELLOUT);
echo $f->format(123456);
In case of using Yii2 you can do this as simple as the following:
$sum = 100500;
echo Yii::$app->formatter->asSpellout($sum);
This prints spelled out $sum in your app's language.
Docs reference
Ok so I am trying to turn my hit counter to round thousands to a single digit too display 3 thousand hits as 3K for example, like the Facebook Share and Twitter Tweet Buttons do. Here is my code. Any idea what I am doing wrong?
$postresultscount = (($resultscount) ? $resultscount->sumCount : 1);
$k = 1000;
$L = '';
if ($postresultscount > $k) {
$echoxcount = round($postresultscount/$k);
$L = 'K';
} else if ($postresultscount == $k) {
$echoxcount = 1;
$L = 'K';
} else {
$echoxcount = $postresultscount;
}
echo 'document.write("'.$echoxcount.' '.$L.'")';
Here comes a PHP function to format numbers to nearest thousands such as Kilos, Millions, Billions, and Trillions with comma
Function
function thousandsCurrencyFormat($num) {
if($num>1000) {
$x = round($num);
$x_number_format = number_format($x);
$x_array = explode(',', $x_number_format);
$x_parts = array('k', 'm', 'b', 't');
$x_count_parts = count($x_array) - 1;
$x_display = $x;
$x_display = $x_array[0] . ((int) $x_array[1][0] !== 0 ? '.' . $x_array[1][0] : '');
$x_display .= $x_parts[$x_count_parts - 1];
return $x_display;
}
return $num;
}
Output
thousandsCurrencyFormat(3000) - 3k
thousandsCurrencyFormat(35500) - 35.5k
thousandsCurrencyFormat(905000) - 905k
thousandsCurrencyFormat(5500000) - 5.5m
thousandsCurrencyFormat(88800000) - 88.8m
thousandsCurrencyFormat(745000000) - 745m
thousandsCurrencyFormat(2000000000) - 2b
thousandsCurrencyFormat(22200000000) - 22.2b
thousandsCurrencyFormat(1000000000000) - 1t (1 trillion)
Resources
https://code.recuweb.com/2018/php-format-numbers-to-nearest-thousands/
function shortNumber($num)
{
$units = ['', 'K', 'M', 'B', 'T'];
for ($i = 0; $num >= 1000; $i++) {
$num /= 1000;
}
return round($num, 1) . $units[$i];
}
I adapted this one from a function created to display bytes in human readable form by bashy here:
https://laracasts.com/discuss/channels/laravel/human-readable-file-size-and-time
a bit better than the post of Yuki
if ($value > 999 && $value <= 999999) {
$result = floor($value / 1000) . ' K';
} elseif ($value > 999999) {
$result = floor($value / 1000000) . ' M';
} else {
$result = $value;
}
Question is 8 years old but each time I see an answer that contains an else statement, I think it can be done in a better (cleaner) way.
<?php
if (!function_exists('format_number_in_k_notation')) {
function format_number_in_k_notation(int $number): string
{
$suffixByNumber = function () use ($number) {
if ($number < 1000) {
return sprintf('%d', $number);
}
if ($number < 1000000) {
return sprintf('%d%s', floor($number / 1000), 'K+');
}
if ($number >= 1000000 && $number < 1000000000) {
return sprintf('%d%s', floor($number / 1000000), 'M+');
}
if ($number >= 1000000000 && $number < 1000000000000) {
return sprintf('%d%s', floor($number / 1000000000), 'B+');
}
return sprintf('%d%s', floor($number / 1000000000000), 'T+');
};
return $suffixByNumber();
}
}
dump(format_number_in_k_notation(123)); // "123"
dump(format_number_in_k_notation(73000)); // "73K+"
dump(format_number_in_k_notation(216000)); // "216K+"
dump(format_number_in_k_notation(50400123)); // "50M+"
dump(format_number_in_k_notation(12213500100600)); // "12T+"
die;
function print_number_count($number) {
$units = array( '', 'K', 'M', 'B');
$power = $number > 0 ? floor(log($number, 1000)) : 0;
if($power > 0)
return #number_format($number / pow(1000, $power), 2, ',', ' ').' '.$units[$power];
else
return #number_format($number / pow(1000, $power), 0, '', '');
}
My func
function numsize($size,$round=2){
$unit=['', 'K', 'M', 'G', 'T'];
return round($size/pow(1000,($i=floor(log($size,1000)))),$round).$unit[$i];
}
Use floor instead of round if you want 3500 to round down to 3 K.
Otherwise, your code works, albeit problematically. Try this:
if ($postresultscount > 1000) {
$result = floor($postresultscount / 1000) . 'K';
} else {
$result = $postresultscount;
}
echo 'document.write("' . $result . '")";
It also appears you're writing JavaScript using PHP—take care.
This is a modified version with k and m lowercase and show one decimal place for milllions.
<?php
if ($value > 999 && $value <= 999999) {
$result = floor($value / 1000) . 'k';
} elseif ($value > 999999) {
$result = number_format((float)$value , 1, '.', '')/1000000 . 'm';
} else {
$result = $value;
}
?>
Several good answers have already been given to this particularly old question, however, most are too simple for my taste or not easy to extend for more units, so here's what I use:
# The function that returns a number formatted as a string in thousands, millions etc.
public static function getNumberAbbreviation (Int $number, Int $decimals = 1) : String {
# Define the unit size and supported units.
$unitSize = 1000;
$units = ["", "K", "M", "B", "T"];
# Calculate the number of units as the logarithm of the absolute value with the
# unit size as base.
$unitsCount = ($number === 0) ? 0 : floor(log(abs($number), $unitSize));
# Decide the unit to be used based on the counter.
$unit = $units[min($unitsCount, count($units) - 1)];
# Divide the value by unit size in the power of the counter and round it to keep
# at most the given number of decimal digits.
$value = round($number / pow($unitSize, $unitsCount), $decimals);
# Assemble and return the string.
return $value . $unit;
}
I created my own method inspired by Twitter.
Function:
function legibleNumb($numb, $lang = 'en') {
if ($lang == 'tr') { // Usage with commas in Turkish
if ($numb >= 1000000) { // Million
if (strstr(round(number_format($numb,0,',','.'),1),'.')) {
$legibleNumb = number_format(round(number_format($numb,0,',','.'),1),1,',','.') . ' Mn';
} else {
$legibleNumb = round(number_format($numb,0,',','.'),1) . ' Mn';
}
} elseif ($numb >= 100000 && $numb < 1000000) { // One hundred thousand
$legibleNumb = round(number_format($numb,0,',','.'),0) . ' B';
} elseif ($numb >= 10000 && $numb < 100000) { // Ten thousand
if (strstr(round(number_format($numb,0,',','.'),1),'.')) {
$legibleNumb = number_format(round(number_format($numb,0,',','.'),1),1,',','.') . ' B';
} else {
$legibleNumb = round(number_format($numb,0,',','.'),1) . ' B';
}
} else {
$legibleNumb = number_format($numb,0,',','.');
}
} else { // Dotted usage in English
if ($numb >= 1000000) { // Million
$legibleNumb = round(number_format($numb,0,',','.'),1) . ' M';
} elseif ($numb >= 100000 && $numb < 1000000) { // One hundred thousand
$legibleNumb = round(number_format($numb,0,',','.'),0) . ' K';
} elseif ($numb >= 10000 && $numb < 100000) { // Ten thousand
$legibleNumb = round(number_format($numb,0,',','.'),1) . ' K';
} else {
$legibleNumb = number_format($numb,0,',','.');
}
}
return $legibleNumb;
}
Usage:
echo legibleNumb(9999999,'en');
echo legibleNumb(9999999,'tr');
echo legibleNumb(54669,'en');
echo legibleNumb(54669,'tr');
echo legibleNumb(5466,'en');
echo legibleNumb(5466,'tr');
Results:
10 M
10 Mn
54.7 K
54,7 B
5.466
5.466
You can try it here and check out sample usages: https://glot.io/snippets/eljyd9ssjx
if ($postresultscount > 999999) {
$postresultscount = floor($postresultscount / 1000000) . ' M';
}
elseif ($postresultscount > 999) {
$postresultscount = floor($postresultscount / 1000) . ' K';
}
echo $postresultscount;
This questuion have the same goal as this question in here Shorten long numbers to K/M/B?
Reference:
https://gist.github.com/RadGH/84edff0cc81e6326029c
Try this code:
function number_format_short( $n, $precision = 1 ) {
if ($n < 900) {
// 0 - 900
$n_format = number_format($n, $precision);
$suffix = '';
} else if ($n < 900000) {
// 0.9k-850k
$n_format = number_format($n / 1000, $precision);
$suffix = 'K';
} else if ($n < 900000000) {
// 0.9m-850m
$n_format = number_format($n / 1000000, $precision);
$suffix = 'M';
} else if ($n < 900000000000) {
// 0.9b-850b
$n_format = number_format($n / 1000000000, $precision);
$suffix = 'B';
} else {
// 0.9t+
$n_format = number_format($n / 1000000000000, $precision);
$suffix = 'T';
}
// Remove unecessary zeroes after decimal. "1.0" -> "1"; "1.00" -> "1"
// Intentionally does not affect partials, eg "1.50" -> "1.50"
if ( $precision > 0 ) {
$dotzero = '.' . str_repeat( '0', $precision );
$n_format = str_replace( $dotzero, '', $n_format );
}
return $n_format . $suffix;
}
The code above create a function to convert the numbers. To use this function later just call it like in the code below:
// Example Usage:
number_format_short(7201); // Output: 7.2k
Rounding up, not accounting for any abbreviations above 'k' or thousands, showing one decimal place.
function numToKs($number) {
if ($number >= 1000) {
return number_format(($number / 1000), 1) . 'k';
} else {
return $number;
}
}
numToKs(1) = 1
numToKs(111) = 111
numToKs(999) = 999
numToKs(1000) = "1.0k"
numToKs(1499) = "1.5k"
numToKs(1500) = "1.5k"
numToKs(1501) = "1.5k"
numToKs(1550) = "1.6k"
numToKs(11501) = "11.5k"
numToKs(1000000000) = "1,000,000.0k"
numToKs(1234567890) = "1,234,567.9k"