1. 程式人生 > 實用技巧 >PHP函式number_format()

PHP函式number_format()

PHP的number_format() 函式通過千位分組來格式化數字。

語法:

number_format(number,decimals,decimalpoint,separator)

註釋:該函式支援一個、兩個或四個引數(不是三個)。

 1 <?php
 2 /* number_format() 函式通過千位分組來格式化數字。
 3 *  該函式支援一個、兩個或者四個引數(注意不是三個)
 4 *  number_format(number,decimals,decimalpoint,separator)
 5 *  第一個引數number,必須,要格式化的數字。如果未設定其他引數,則數字會被格式化為不帶小數點且以(,)作為千位分隔符
6 * 第二個引數decimals,可選,規定多少個小數。如果設定了該引數,則使用點號(.)作為小數點來格式化數字; 7 * 第三個引數,decimalpoint。可選。規定用作小數點的字串 8 * 第四個引數,separator.可選.規定用做千位分割符的字串.僅使用該引數的第一個字元。比如 "xxx" 僅輸出 "x"。 註釋:如果設定了該引數,那麼所有其他引數都是必需的。 9 */ 10 $number = 10001.999; 11 $formatNum1 = number_format($number); 12 echo $formatNum1; //輸出10,002 13 echo "<br/>";
14 $formatNum2 = number_format($number,2); 15 echo $formatNum2; //輸出10,002.00 16 echo "<br/>"; 17 $formatNum3 = number_format($number,2,'x','!'); 18 echo $formatNum3; //輸出10!002x00 19 echo "<br/>"; 20 21 22 /* 23 * Build the program's capability - define variables and functions... 24 */ 25 26 $item_label
= ''; // String 27 $item_price = 0.0; // Float 28 $item_qty = 1; // Tnteger 29 $item_total = 0.0; // Float - set to use function calculate() 30 31 // 定義函式用以計算 32 function start_calculate(){ 33 global $item_price, $item_qty, $item_total; 34 $item_price = number_format($item_price,2); //呼叫number_format()格式化數字 35 $item_total = number_format(($item_price * $item_qty),2); 36 } 37 38 // 定義函式用於輸出 39 function itemToString(){ 40 global $item_label, $item_price, $item_qty, $item_total; 41 return "$item_label: [Price = \$$item_price, Quality = $item_qty, Total = \$$item_total]"; 42 } 43 44 /* 45 * Run the program - set data, call methods... 46 */ 47 $item_label = "Coffee"; 48 $item_price = 3.89; 49 $item_qty = 2; 50 start_calculate(); 51 echo itemToString(); 52 53 echo "<br/>"; 54 55 $item_label = "Chicken"; 56 $itme_price = .80; 57 $item_qty = 3.5; 58 start_calculate(); 59 echo itemToString(); 60 61 ?>

宣告:程式碼並沒有實際意義,僅供學習和交流使用。