I'd like to convert currency values like this:
4 000 000 000 => 4b
2 000 000 => 2m
2 250 000 => 2.25m
195 000 => 195k
10 000 => 10k
Anyone know of an existing library/function that does this, or do I need to write this myself by means of conditionals that cater for 0-9999, 10000-999999, and so on..?
You can create a custom function for this. The below one, firstly removes everything but numbers from string. Then it formats the number according how big is it and to the digit provided.
function shorten($num, $digits = 1) {
$num = preg_replace('/[^0-9]/','',$num);
if ($num >= 1000000000) {
$num = number_format(($num / 1000000000), $digits, '.', '') + 0;
$num = $num . "b";
}
if ($num >= 1000000) {
$num = number_format(($num / 1000000), $digits, '.', '') + 0;
$num = $num . 'm';
}
if ($num >= 1000) {
$num = number_format(($num / 1000), $digits, '.', '') + 0;
$num = $num . 'k';
}
return $num;
}
echo shorten("4 000 000 000");
echo shorten("3 200 000 000");
echo shorten("195 000");