Home  >  Article  >  Backend Development  >  php怎么保留2位小数

php怎么保留2位小数

PHPz
PHPzOriginal
2016-06-02 11:30:575765browse

方法:1、使用round()函数进行四舍五入,语法“round(浮点数,2)”;2、利用sprintf()函数,语法“sprintf("%.2f", 浮点数)”;3、使用format()函数进行四舍五入,语法“format(浮点数,2)”。

php怎么保留2位小数

php怎么保留2位小数?

$num = 4.30258;
//第一种:利用php round方法对浮点数进行四舍五入
echo round($num, 2); //4.30
     
//第二种:利用sprintf格式化字符串
$format_num = sprintf("%.2f", $num);
echo $format_num; //4.30
     
//第三种:利用千位分组来格式化数字的函数number_format()
echo number_format($num, 2, ".", ""); //4.30
//第四种:利用mysql format函数对浮点数进行四舍五入
seletc format(num, 2); //4.30

当$num为超过两位小数时是都可以使用,但是如果在thinkphp当中是小于两位需格式化则只能使用第二、三、四种,如果对格式不能允许逗号存在则只能使用第二、三种。

更多相关知识,请访问PHP中文网

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