请选择 进入手机版 | 继续访问电脑版

PHP保留两位小数的几种方法教程

[复制链接]
查看1800 | 回复0 | 2020-10-29 14:08 | 显示全部楼层 |阅读模式

主要介绍了PHP保留两位小数的几种方法,在一些商品价格上也经常遇到这样的需求,代码如下:
  1. $num = 10.4567;  
  2.   //第一种:利用round()对浮点数进行四舍五入
  3.   echo round($num,2); //10.46
  4.    
  5.   //第二种:利用sprintf格式化字符串
  6.   $format_num = sprintf("%.2f",$num);
  7.   echo $format_num; //10.46
  8.    
  9.   //第三种:利用千位分组来格式化数字的函数number_format()
  10.   echo number_format($num, 2); //10.46
  11.   //或者如下
  12.   echo number_format($num, 2, '.', ''); //10/46
复制代码
ps:PHP 数字(价格)保留两位小数
下面看下PHP中对一些商品的价格计算或价格的的展示,需要精确到小数点后的两位数字,也就是我们平时RMB中的分的单位。那在PHP中如何展示商品的价格,并保留到分的单位的呢?下面教程就来讲解一下。
php 商品价格,php保留两位小数,php商品价格展示
PHP number_format() 函数
number_format():函数可以通过千位分组的形式来格式化数字。
语法:
number_format(number,decimals,decimalpoint,separator)
参数:
number:必需。要格式化的数字。
decimals:可选。规定多少个小数。
decimalpoint:可选。规定用作小数点的字符串。
separator:可选。规定用作千位分隔符的字符串。

例:PHP商品价格以元为单位,保留两位小数
  1. <?php
  2. $a = 10;
  3. echo number_format($a,'2');
  4. $b = 1000000;
  5. echo number_format($b,'2');
  6. $c = 5458.5684;
  7. echo number_format($c,'2');
  8. $d = '1254.8963';
  9. echo number_format($d,'2');
  10. $e = '88.9643';
  11. echo number_format($e,'2');
  12. ?>
复制代码
输出结果:
10.00
1,000,000.00
5,458.57
1,254.90
88.96

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

UID
1
贡献
387
丢币
38902
主题
4607
回帖
116
注册时间
2018-9-25
最后登录
2024-3-24