Home >php教程 >PHP源码 >PHP保留两位小数 四舍五入方法

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-08 17:24:122203browse

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

<script>ec(2);</script>

方法一

sprintf()函数 ,sprintf() 函数把格式化的字符串写写入一个变量中

 代码如下 复制代码

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

例2

 代码如下 复制代码

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

输出:

123.000000

方法二 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() 函数对浮点数进行四舍五入。

例子

 代码如下 复制代码

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn