2011-12-18 56 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