首页 > php开发 > PHP保留两位小数 四舍五入方法

PHP保留两位小数 四舍五入方法

在php中要保留两位小数的方法有很多种办法,有如:sprintf,substr,number_format,round等等方法,下面我来给大家介绍介绍.

方法一,sprintf()函数,sprintf() 函数把格式化的字符串写写入一个变量中,代码如下:

$num = 123213.666666;   
echo sprintf("%.2f", $num);

PHP实例代码如下:

<?php 
$number = 123; 
$txt = sprintf("%f",$number); 
echo $txt; 
?>

方法二,substr()函数,代码如下:

$num = 123213.666666;   
echo sprintf("%.2f",substr(sprintf("%.3f", $num), 0, -2));

方法三 number_format()函数,代码如下:

$number = 1234.5678; 
$nombre_format_francais = number_format($number, 2, ',', ' '); // 1234,57 
$english_format_number = number_format($number, 2, '.', '');   // 1234.57(我一般用这个)

方法四,round 函数,round() 函数对浮点数进行四舍五入,实例代码如下:

<?php 
echo(round(0.60)); 
echo(round(0.50)); 
echo(round(0.49)); 
echo(round(-4.40)); 
echo(round(-4.60)); 

/*输出: 
1 
1 
0 
-4 
-5 
*/
?>

如果要保留小数,后来参数根保留小数位数即可,代码如下:

$number = 1234.5678; 
echo round($number ,2); //1234.57

               
               

本文地址:http://www.phprm.com/develop/fs3983.html

转载随意,但请附上文章地址:-)

标签:php保留两位小数 php四舍五入

发表留言