当前位置:网站首页>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
边栏推荐
- Minikube initial experience environment construction
- Business visualization - make your flowchart'run'(4. Actual business scenario test)
- 配置Jupyter远程服务器
- Direct insert sort and Hill sort
- SkiaSharp 之 WPF 自绘 拖曳小球(案例版)
- Traversal and copy of files in jar package
- 什么是WordPress
- php⽉份加减最简单的处理⽅法
- Docker runs MySQL service
- Some knowledge concepts
猜你喜欢

IDEA复制模块

Application of mobile face stylization Technology
![[leetcode] 8. binary search · binary search](/img/35/c4ff66c124754c2a9a7d63b8040e4a.png)
[leetcode] 8. binary search · binary search

STL の 概念及其应用

The principle and use of the wrap file of tolua

15、用户web层服务(三)

Untiy controls the playback speed of animation

Globalthis is not defined solution

Unity encountered a pitfall and the AB package failed to unload

Unity中使用UnityWebRequest进行网络和本地图片加载
随机推荐
业务可视化-让你的流程图'Run'起来(4.实际业务场景测试)
Update dev (development version) of the latest win11
LyScript 获取上一条与下一条指令
强缓存、协商缓存具体过程
Develop your own NPM package from 0
如何让照片中的人物笑起来?HMS Core视频编辑服务一键微笑功能,让人物笑容更自然
The principle and use of the wrap file of tolua
Yolov3 complete explanation - from the perspective of data coding
Alexnet - paper analysis and reproduction
[diary of supplementary questions] [2022 Niuke summer multi school 2] l-link with level editor I
The game process and the underlying implementation are gradually completed
Interfaces and abstract classes
Go deadlock - when the channel meets mutex
Test platform (V) knowledge points supplement
Unity encountered a pitfall and the AB package failed to unload
AlexNet—论文分析及复现
Pycharm debugging mode
本地化、低时延、绿色低碳:阿里云正式启用福州数据中心
async await如何实现并发
boost官网搜索引擎项目详解