1

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:

  • B illion
  • M illion
1

2 Answers 2

3

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';
     }
}

http://codepad.org/nb89ze5J

Sign up to request clarification or add additional context in comments.

1 Comment

@Jackson, now I noticed it does not return what you wanted for the second number (it's giving 12.35B instead of 12.354B), but I believe this code should work as a starting point anyway...
0

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

2 Comments

I added some more clarification on the B and M abbreviations in my question edit. I failed to evaluate the clarity of my question correctly :(
@Jackson: Then take a look at this comment on the same page: php.net/manual/en/function.number-format.php#89888

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.