Skip to content

Instantly share code, notes, and snippets.

@prezire
Last active December 21, 2017 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prezire/f58d7a0fd7080ac447550e07124c9e9d to your computer and use it in GitHub Desktop.
Save prezire/f58d7a0fd7080ac447550e07124c9e9d to your computer and use it in GitHub Desktop.
CI 3 or 4 number helper with large number abbreviations.
<?php
function number_to_amount($value, bool $abbreviate = false):string
{
$iLimit = 90;
$sLimit = 'Octovigintillion';
if(strlen($value) > $iLimit)
{
throw new Exception("The value must not exceed $sLimit.");
}
$unit = '';
$symbol = $abbreviate ? 'K' : 'Thousand';
$iThousand = 1000;
while($value >= $iThousand)
{
$value /= $iThousand;
$unit .= $symbol;
}
$units =
[
['Million', 'M'],
['Billion', 'B'],
['Trillion', 't'],
['Quadrillion', 'q'],
['Quintillion', 'Q'],
['Sextillion', 's'],
['Septillion', 'S'],
['Octillion', 'o'],
['Nonillion', 'n'],
['Decillion', 'd'],
['Undecillion', 'U'],
['Duodecillion', 'D'],
['Tredecillion', 'T'],
['Quattuordecillion', 'Qt'],
['Quindecillion', 'Qd'],
['Sexdecillion', 'Sd'],
['Septendecillion', 'St'],
['Octodecillion', 'O'],
['Novemdecillion', 'N'],
['Vigintillion', 'v'],
['Unvigintillion', 'c'],
['Duovigintillion', 'e69'],
['Trevigintillion', 'e72'],
['Quattuorvigintillion', 'e75'],
['Quinvigintillion', 'e78'],
['Sesvigintillion', 'e81'],
['Septenvigintillion', 'e84'],
[$sLimit, 'e87']
];
$j = count($units);
for($i = $j - 1; $i > -1; $i--)
{
$iSymbolOffset = 2;
$search = str_repeat($symbol, $i + $iSymbolOffset);
$replace = $units[$i][$abbreviate];
$unit = str_replace($search, $replace, $unit);
}
$separator = $abbreviate ? '': ' ';
$amt = $value. $separator . $unit;
return $abbreviate ? $amt : strtolower($amt);
}
function init()
{
foreach(range(0, 90) as $i)
{
$zeros = str_repeat('0', $i);
$i = (int)1 . $zeros;
$amt = number_to_amount($i, true);
echo $i, ' = ', $amt, "<br>\r\n";
}
}
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment