Show 1k instead of 1000

function restyle_text($input){ $input = number_format($input); $input_count = substr_count($input, ','); if($input_count != '0'){ if($input_count == '1'){ return substr($input, +4).'k'; } else if($input_count == '2'){ return substr($input, +8).'mil'; } else if($input_count == '3'){ return substr($input, +12).'bil'; } else { return; } } else { return $input; } } 

This is the code that I have, I thought it worked. apparently not .. can someone help, since I can’t figure it out.

+7
source share
4 answers

Try the following:

http://codepad.viper-7.com/jfa3uK

 function restyle_text($input){ $input = number_format($input); $input_count = substr_count($input, ','); if($input_count != '0'){ if($input_count == '1'){ return substr($input, 0, -4).'k'; } else if($input_count == '2'){ return substr($input, 0, -8).'mil'; } else if($input_count == '3'){ return substr($input, 0, -12).'bil'; } else { return; } } else { return $input; } } 

Basically, I think you are using substr() incorrectly.

+8
source

Here is a general way to do this that does not require the use of number_format or parsing strings:

 function formatWithSuffix($input) { $suffixes = array('', 'k', 'm', 'g', 't'); $suffixIndex = 0; while(abs($input) >= 1000 && $suffixIndex < sizeof($suffixes)) { $suffixIndex++; $input /= 1000; } return ( $input > 0 // precision of 3 decimal places ? floor($input * 1000) / 1000 : ceil($input * 1000) / 1000 ) . $suffixes[$suffixIndex]; } 

And here is a demo showing that it works correctly for several cases.

+6
source

I re-wrote the function to use the properties of numbers, and not play with strings.

It should be faster.

Let me know if I missed any of your requirements:

 function restyle_text($input){ $k = pow(10,3); $mil = pow(10,6); $bil = pow(10,9); if ($input >= $bil) return (int) ($input / $bil).'bil'; else if ($input >= $mil) return (int) ($input / $mil).'mil'; else if ($input >= $k) return (int) ($input / $k).'k'; else return (int) $input; } 
+3
source

I don't want to ruin the moment ... but I think it is a little simplified.

Just improving @Indranil's answer

eg.

 function comp_numb($input){ $input = number_format($input); $input_count = substr_count($input, ','); $arr = array(1=>'K','M','B','T'); if(isset($arr[(int)$input_count])) return substr($input,0,(-1*$input_count)*4).$arr[(int)$input_count]; else return $input; } echo comp_numb(1000); echo '<br />'; echo comp_numb(1000000); echo '<br />'; echo comp_numb(1000000000); echo '<br />'; echo comp_numb(1000000000000); 
+1
source

All Articles