Reputation: 32207
Let's say I have numbers like
123456000000
12345000000
123456000
123456
and I want them to show up as
123.45B
12.345B
123.45M
123,456
The best way I can think of to do this is by getting string length to determine if I need a B, M, or nothing but commas and just substr
the first five chars. I'm sure there is a better way though and I don't want to get too far before I realize that my idea sucks. hah.
Any good recommendations?
EDIT
My apologies on the confusion of the B and M. Those represent:
Upvotes: 1
Views: 278
Reputation: 71918
Okay, so my previous answer considered you were dealing with file sizes, and I deleted it. However the logic of this solution is the same:
function format_number($num) {
if($num < 1000000) {
return number_format($num);
} elseif ($num < 1000000000) {
return number_format($num/1000000, 2) . 'M';
} else {
return number_format($num/1000000000, 2) . 'B';
}
}
Upvotes: 3
Reputation: 29166
Don't know about the last B
or M
part but there is a function called number_format in PHP which does the following (from the documentation) -
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
Upvotes: 0