PHP如何使用number_format()函数?示例

2021年3月24日14:53:02 发表评论 633 次浏览

number_format()函数是PHP中的内置函数, 用于格式化成千上万个数字。成功时返回格式化的数字, 否则返回E_WARNING。

语法如下:

string number_format ( $number, $decimals, $decimalpoint, $sep )

参数:该函数接受上述和以下所述的四个参数:

  • $ number:这是必需的参数, 用于指定要格式化的编号。如果未设置其他参数, 则数字的格式将不带小数, 以逗号(, )作为千位分隔符。
  • $ decimals:它是可选参数, 用于指定小数。如果设置了此参数, 则数字将以点(。)作为小数点格式。
  • $ decimalpoint:它是可选参数, 用于指定用于小数点的字符串。
  • $ sep:它是可选参数, 用于指定用于千位分隔符的字符串。如果给出此参数, 则所有其他参数都是必需的。

返回值:如果成功, 则返回格式化数字, 否则返回E_WARNING失败。

例子:

Input: $number = 100000
Output: 10, 000

Input: $number = 10000 
       $decimals = 3 
       $decimalpoints = "." $sep =, Output: 10, 0000.000

下面的程序说明了PHP中的number_format()函数:

程序1:

<?php
$num1 = "999999.49" ;
  
// With out decimal point parameter
echo number_format( $num1 ). "\n" ;
  
// With decimal Point parameter
echo number_format( $num1 , 3). "\n" ;
   
$num2 = "9999999.99" ;
  
// With out decimal point parameter
// return Round value
echo number_format( $num2 ). "\n" ;
  
// With decimal Point parameter
echo number_format( $num2 , 3). "\n" ; 
  
// With All four parameters
echo number_format( "1000000.99" , 3, "#" , "GGG" );
  
   
?>

输出如下:

999, 999
999, 999.490
10, 000, 000
9, 999, 999.990
1GGG000GGG000#990

程式2:如果传递任何内容而不是数字, 则会发出警告。

<?php
$num = "GFG" ;
  
// With out decimal point parameter
echo number_format( $num ). "\n\n" ;
  
// With decimal Point parameter
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

程式3:此函数不接受三个参数, 仅接受1、2或4个参数。

<?php
$num = 1000000;
  
// passing 3 parameters It gives errors because function
// accepting only 1, 2 or 4 parameters
echo number_format( $num , 3, ", " );
?>

输出如下

:

PHP Warning:  Wrong parameter count for number_format() 
in /home/e426108b066d9a86366249bf7b626d19.php on line 6

参考: http://php.net/manual/en/function.number-format.php


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: