如何使用php number_format函数

如何使用php number_format函数

如何使用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

关于如何使用php number_format函数问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。