Created
June 12, 2013 22:40
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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