Skip to content

Instantly share code, notes, and snippets.

@cfg
Created June 12, 2013 22:40
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 cfg/5769768 to your computer and use it in GitHub Desktop.
Save cfg/5769768 to your computer and use it in GitHub Desktop.
Take an abbreviated number in the format of 1M, 500K and 2.5k and return 1000000, 500000 and 2500 respectively.
<?php
function number_longhand( $num ) {
$is_array = is_array( $num );
if( !$is_array )
$num = array( $num );
$num = preg_replace( '/[^\d\.BMK]/i', '', $num );
foreach( $num as $index => $n ) {
switch( $n[strlen($n) - 1] ) {
case 'B':
case 'b':
$n *= 1000000000;
break;
case 'M':
case 'm':
$n *= 1000000;
break;
case 'K':
case 'k':
$n *= 1000;
break;
}
$num[$index] = $n;
}
if( !$is_array )
return $num[0];
else
return $num;
}
$numbers = array(
'1m',
'.5m',
'254 k',
'1.2 M',
'1,200',
'1500',
'0',
'1.5',
);
foreach( $numbers as $n ) {
$f = number_longhand( $n );
printf( "%s = %s = %s<br>", $n, $f, number_format( $f, 2 ) );
}
echo '<hr>';
var_dump( number_longhand( $numbers ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment