2012-04-19 41 views
3

有沒有簡單的方法來轉換高數字,例如用PHP 14120000轉換成1412萬的格式?將數字轉換爲xx.xx百萬格式?

我一直在看number_format,但它似乎並沒有提供這個功能,也想到sub_str將數字分開,但認爲可能有更好的方法?

+0

[你嘗試過什麼(http://mattgemmell.com/2008/12/08/what-have-you-tried/)? – Lion 2012-04-19 04:38:18

+0

我一直在看number_format,但它似乎並沒有提供這個功能,也想到sub_str分開數字出來,但認爲可能有更好的辦法? – Chris 2012-04-19 04:39:35

+0

也許他不知道從哪裏開始,並尋求建議?這是一個難以理解的概念嗎? – Jack 2012-04-19 05:31:17

回答

25

從,https://php.net/manual/en/function.number-format.php#89888試試這個:

<?php 
    function nice_number($n) { 
     // first strip any formatting; 
     $n = (0+str_replace(",", "", $n)); 

     // is this a number? 
     if (!is_numeric($n)) return false; 

     // now filter it; 
     if ($n > 1000000000000) return round(($n/1000000000000), 2).' trillion'; 
     elseif ($n > 1000000000) return round(($n/1000000000), 2).' billion'; 
     elseif ($n > 1000000) return round(($n/1000000), 2).' million'; 
     elseif ($n > 1000) return round(($n/1000), 2).' thousand'; 

     return number_format($n); 
    } 

echo nice_number('14120000'); //14.12 million 

?> 
+1

謝謝你的工作很好。認爲可能有一個更通用的PHP函數,但顯然不是! – Chris 2012-04-19 04:54:21

+2

你不應該引用這個嗎? http://php.net/manual/en/function.number-format.php#89888 – Anuj 2015-10-10 12:24:50

+0

替代解決方案:http://kahthong.com/2013/01/php-format-currency-nearest-thousands-such-kilos - 數百萬億 - 數萬億 – 2015-11-04 02:44:33