2011-12-18 95 views
7
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; 
    } 
} 

这是我的代码,我认为它工作。显然不是......可以有人帮助,因为我无法弄清楚这一点。显示1k而不是1,000

+1

当您运行此代码时,您收到了什么?你有没有收到任何错误?如果是,那么哪个? – Lion 2011-12-18 02:42:52

+1

这是做什么,“不工作”? – 2011-12-18 02:43:04

+0

可能重复[缩短长号到K/M/B?](http://stackoverflow.com/questions/4371059/shorten-long-numbers-to-kmb) – 2011-12-18 02:50:51

回答

8

试试这个:

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

基本上,我认为你正在使用的substr()错误。

3

我重写了函数来使用数字的属性而不是用字符串来玩。

这应该会更快。

让我知道如果我错过了你的任何要求:

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

这里是可以做到这一点并不需要您使用number_format或做字符串分析的一般方法:

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

并且在几种情况下可以使用here's a demo showing it working correctly

+0

感谢很多伴侣,作品像一个魅力 – 2014-02-12 11:39:53

1

我不想破坏那一刻......但我认为这有点简化了。

只是提高@Indranil答案

例如

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); 
+0

这忽略了十进制 - 例如:1250 – 2014-02-12 11:39:37

+0

所以还有其他答案。 =) – 2018-03-05 13:58:44