Convert 1000 to k format in php

There are times when we need to display our currency in K, M and B format. As our currency becomes to long to manage.

Here is a little function which takes the integer value and returns the short form like 1k, 1M and 1B.

The second parameter is precision. It limits the result to limited decimal points. The default decimal point is two.


  function format_num($num, $precision = 2) {
   if ($num >= 1000 && $num < 1000000) {
    $n_format = number_format($num/1000,$precision).'K';
    } else if ($num >= 1000000 && $num < 1000000000) {
    $n_format = number_format($num/1000000,$precision).'M';
   } else if ($num >= 1000000000) {
   $n_format=number_format($num/1000000000,$precision).'B';
   } else {
   $n_format = $num;
    }
  return $n_format;
  } 


// Function Calls

echo format_num(1200,1);
echo format_num(1230000);
echo format_num(1234000000,3);
Convert 1000 to k format in php Convert 1000 to k format in php Reviewed by Altaf Hussain on 11:14 PM Rating: 5

1 comment:

Altaf Web. Powered by Blogger.