10

Is there a simple way to convert a high number e.g. 14120000 into 14.12 million format with PHP?

I've been looking at number_format but it doesn't seem to offer this function, also thought about sub_str to separate the digits out, but thought there might be a better way?

Chris
  • 1,557
  • 5
  • 19
  • 36
  • [What have you tried](http://mattgemmell.com/2008/12/08/what-have-you-tried/)? – Lion Apr 19 '12 at 04:38
  • I've been looking at number_format but it doesn't seem to offer this function, also thought about sub_str to separate the digits out, but thought there might be a better way? – Chris Apr 19 '12 at 04:39
  • Maybe he doesn't know where to start and is asking for advice? Is that such a hard concept to grasp? – Jack Apr 19 '12 at 05:31
  • Closed as not a real question? Can someone tell me what is not real about this question? Just so I know for the future - thanks. – Chris Apr 28 '12 at 04:13
  • Found a similar question here which has been accepted as valid: http://stackoverflow.com/questions/1068284/format-numbers-in-javascript . It might be more constructive and welcoming for newbies like me to suggest how to improve my question before immediately downvoting me and closing the question without explanation. – Chris Apr 28 '12 at 04:24
  • This is a perfectly valid question & one I was going to ask. Not sure why it was closed. The fact that someone could actually answer it, proves that it was a valid question more than anything else. – Vunus Mar 04 '14 at 15:14
  • Yeah I don't know what's up with SO anymore – Chris Mar 27 '14 at 10:28

1 Answers1

48

Try this from, https://php.net/manual/en/function.number-format.php#89888:

<?php 
    function nice_number($n) {
        // first strip any formatting;
        $n = (0+str_replace(",", "", $n));

        // is this a number?
        if (!is_numeric($n)) return false;

        // now filter it;
        if ($n > 1000000000000) return round(($n/1000000000000), 2).' trillion';
        elseif ($n > 1000000000) return round(($n/1000000000), 2).' billion';
        elseif ($n > 1000000) return round(($n/1000000), 2).' million';
        elseif ($n > 1000) return round(($n/1000), 2).' thousand';

        return number_format($n);
    }

echo nice_number('14120000'); //14.12 million

?>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
  • 1
    Thanks this works great. Thought there might be a more general PHP function for this, but obviously not! – Chris Apr 19 '12 at 04:54
  • 3
    Shouldn't you cite to this? http://php.net/manual/en/function.number-format.php#89888 – Anuj Oct 10 '15 at 12:24
  • Alternative solution: http://kahthong.com/2013/01/php-format-currency-nearest-thousands-such-kilos-millions-billions-and-trillions – Brighton Vino Nov 04 '15 at 02:44
  • 1
    Why did you close this question? The algorythm above is ugly and better solutions are possible. – lubosdz Dec 10 '16 at 14:53