codingtcher.com
Theme Night
Home
Login

Shorten long numbers to K M B T short number format php convert 1000 to 1K

Home » Tutorial Post » PHP Number format to convert 1000 to 1K

function customnumberformat($n, $precision = 1){
  if ($n < 1000) {
      $n_format = number_format($n).' views';
  } 
  else if ($n < 1000000) {
      $n_format = number_format($n / 1000, $precision).'K';
  }
  else if ($n < 1000000000) {
      $n_format = number_format($n / 1000000, $precision).'M';
  } else if ($n < 1000000000000) {
      $n_format = number_format($n / 1000000000, $precision).'B';
  } else {
    $n_format = number_format($n / 1000000000000, $precision).'T';
  }
  return str_replace(array('.0K','.0M','.0B','.0T'),array('K','M','B','T'),$n_format);
}

echo customnumberformat("1500");

//get result 1.5K

Related Post