本篇文章主要給大家介紹php number_format用法,希望對需要的朋友有所幫助!
number_format()函數是PHP中的一個內置函數,用于格式化一個包含數千個分組的數字。它在成功時返回格式化的數字,否則在失敗時給出E_WARNING。
語法:
string number_format ( $number, $decimals, $decimalpoint, $sep )
參數:
該函數接受上述四個參數,如下所述:
$number:它是指定要格式化的數字的必需參數。如果沒有設置其他參數,則該數字將被格式化為不帶小數,并使用逗號(,)作為千位分隔符。必須參數指定要格式化的數字。
$decimals:它是可選參數,用于指定小數。如果設置了此參數,則該數字將使用圓點(.)作為小數點進行格式化。
$decimalpoint:它是一個可選參數,用于指定要用于小數點的字符串。
$sep:它是可選參數,用于指定用于千位分隔符的字符串。如果給定了該參數,則需要所有其他參數。
返回值:
成功時返回格式化的數字,失敗時返回E_WARNING。
number_format()代碼示例1:
- <?php
- $num1 = "999999.49";
- // 沒有小數點參數
- echo number_format($num1)."/n";
- // 帶小數點參數
- echo number_format($num1, 3)."/n";
- $num2 = "9999999.99";
- // 沒有小數點參數
- //返回整數值
- echo number_format($num2)."/n";
- //帶小數點參數
- echo number_format($num2, 3)."/n";
- // 包含所有四個參數
- echo number_format("1000000.99", 3, "#", "GGG");
- ?>
輸出:
999,999
999,999.490
10,000,000
9,999,999.990
1GGG000GGG000#990
number_format()代碼示例2:
如果傳遞任何東西而不是數字,它則會給出警告。
- <?php
- $num = "GFG";
- echo number_format($num)."/n/n";
- echo number_format($num, 3);
- ?>
輸出:
PHP Warning: number_format() expects parameter 1 to be float,
string given in /home/ac476aaecea758334cb8ed146bcbb8f6.php on line 5
PHP Warning: number_format() expects parameter 1 to be float,
string given in /home/ac476aaecea758334cb8ed146bcbb8f6.php on line 8
number_format()代碼示例3:
此函數不接受三個參數,只接受1、2或4個參數。
- <?php
- $num = 1000000;
- echo number_format($num, 3, ", ");
- ?>
輸出:
PHP Warning: Wrong parameter count for number_format()
in /home/e426108b066d9a86366249bf7b626d19.php on line 6
新聞熱點
疑難解答