当前位置:网站首页>php保留两位小数的几种方法介绍
php保留两位小数的几种方法介绍
2022-07-28 11:24:00 【历史老师-】
1.不进位的情况
比如3.149569取小数点后两位,最后两位不能四舍五入。结果:3.14。
可以使用 floor 函数
该函数是舍去取整。例如,floor(4.66456) 结果:4 。
floor(9.1254) 结果9 。
因此,去小数点后两位,需要先乘以100,然后舍去取整,再除以100,即:
$a=floor(3.149569*100)/100
这时浮点计算会出现一个bug,通过php的无类型特性来解决这个问题,先strval转成字符串,再自动识别类型。下面计算百分比已经使用上strval()函数了
计算百分比
$successRate = floor(strval((2/3)*10000))/10000*100; $result = $successRate.'%';
2.四舍五入的情况
round 函数
float round ( float val [, int precision])
返回将 val 根据指定精度 precision(十进制小数点后数字的数目)进行四舍五入的结果。
precision 也可以是负数或零(默认值)。
sprintf 函数
实现四舍五入,并且如果是不带小数位数的,会自动用指定的字符(指定的0)补至指定的小数位数
echo sprintf("%01.2f", 5.228); // 5.23
echo sprintf("%01.2f", 5.224); // 5.22
echo sprintf("%01.2f", 5); // 5.00number_format 函数
如果是不带小数位数的,会自动用0补至指定的小数位数
echo number_format(5.228,2); // 5.23 echo number_format(5.224,2); // 5.22 echo number_format(5,2); // 5.00
round 函数
此函数可以实现四舍五入,但是如果是不带小数位数的,处理后也不带小数数位
echo round(5.228,2); // 5.23 echo round(5.224,2); // 5.22 echo round(5,2); // 5
php进一法取整
echo ceil(4.4); // 5 echo ceil(4.6); // 5
php舍去法取整
echo floor(4.4); // 4 echo floor(4.6); // 4
边栏推荐
猜你喜欢

Ruiji takeout - day01

15、用户web层服务(三)

Interpretable ml of Li Hongyi's machine learning model

瑞吉外卖——Day01

Training mode and practice of digital applied talents in Colleges and Universities under the integration of industry and education

Develop your own NPM package from 0

Untiy controls the playback speed of animation

中国业务型CDP白皮书 | 爱分析报告

Unitywebrequest is used in unity to load network and local pictures

An idea plug-in helps you transform dto, VO, Bo, Po, do gracefully
随机推荐
The game process and the underlying implementation are gradually completed
Yolov3 complete explanation - from the perspective of data coding
consul安装与配置
String function (Part 2)
Launcher sample code
STL concept and its application
Business visualization - make your flowchart'run'(4. Actual business scenario test)
Gecko competition 2.0 is new! Come and show your flexible operation skills!
Minikube initial experience environment construction
Hcip (PAP authentication and chap authentication of PPP)
Interpretable ml of Li Hongyi's machine learning model
Pycharm debugging mode
[general database integrated development environment] Shanghai daoning provides you with Aqua Data Studio downloads, tutorials, and trials
Start from scratch blazor server (2) -- consolidate databases
Know the optical fiber interface and supporting optical fiber cable of can optical fiber converter in fire alarm networking
Test platform (V) knowledge points supplement
LyScript 获取上一条与下一条指令
Redis installation
中国业务型CDP白皮书 | 爱分析报告
P5472 [noi2019] douzhudi (expectation, Mathematics)