当前位置:Gxlcms > PHP教程 > php四舍五入截取浮点型字符串方法总结

php四舍五入截取浮点型字符串方法总结

时间:2021-07-01 10:21:17 帮助过:9人阅读

php中截取浮点型大致有下面几种方法:

1、 float round ( float $val [, int $precision ] ) 返回将 val 根据指定精度 precision (十进制小数点后数字的数目)进行四舍五入的结果。precision 也可以是负数或零(默认值)。

echo round(4.3) //4

2、 string sprintf ( string $format [, mixed $args [, mixed $... ]] ) 返回格式化数据的字符串

  1. $a=12.338938438;
  2. echo sprintf("%.5f",$a) //结果:12.33894
  3. $a=12.3312356;
  4. echo sprintf("%.5f",$a);//12.33124
  5. echo sprintf("%f",$a);//331236 默认小数点后6位

3、 string number_format ( float $number , int $decimals , string $dec_point , string $thousands_sep )

  1. $number = 1234.5678;
  2. $english_format_number = number_format($number, 2, '.', '');
  3. echo $english_format_number ; // 1234.57

以上这些都自动做了四舍五入,有时候需求不需要四舍五入呢,怎么办,没有想到好办法,谁知道可以告诉一声。

自己写了个麻烦点的函数,记录下

  1. function getFloatValue($f,$len)
  2. {
  3. $tmpInt=intval($f);
  4. $tmpDecimal=$f-$tmpInt;
  5. $str="$tmpDecimal";
  6. $subStr=strstr($str,'.');
  7. if(strlen($subStr)<$len+1)
  8. {
  9. $repeatCount=$len+1-strlen($subStr);
  10. $str=$str."".str_repeat("0",$repeatCount);
  11. }
  12. return $tmpInt."".substr($str,1,1+$len);
  13. }
  14. echo getFloatValue(12.99,4) //12.9900
  15. echo getFloatValue(12.9232555553239,4) //12.9232

更多php float不四舍五入截取浮点型字符串方法总结相关文章请关注PHP中文网!

相关文章:

php 数据处理之取整,四舍五入

php中四舍五入取整函数详细介绍

PHP实现四舍五入的3种方法

人气教程排行