php float不四舍五入截取浮点型字符串方法总结
php中截取浮点型大致有下面几种方法:
1、 float round ( float $val [, int $precision ] ) 返回将 val 根据指定精度 precision (十进制小数点后数字的数目)进行四舍五入的结果。precision 也可以是负数或零(默认值)。
echo round(4.3) //4
2、 string sprintf ( string $format [, mixed $args [, mixed $... ]] ) 返回格式化数据的字符串
代码如下:
$a=12.338938438;
echo sprintf("%.5f",$a) //结果:12.33894
$a=12.3312356;
echo sprintf("%.5f",$a);//12.33124
echo sprintf("%f",$a);//331236 默认小数点后6位3、 string number_format ( float $number , int $decimals , string $dec_point , string $thousands_sep )
代码如下:
$number = 1234.5678; $english_format_number = number_format($number, 2, '.', ''); echo $english_format_number ; // 1234.57
以上这些都自动做了四舍五入,有时候需求不需要四舍五入呢,怎么办,没有想到好办法,谁知道可以告诉一声。
自己写了个麻烦点的函数,记录下
代码如下:
function getFloatValue($f,$len)
{
$tmpInt=intval($f);
$tmpDecimal=$f-$tmpInt;
$str="$tmpDecimal";
$subStr=strstr($str,'.');
if(strlen($subStr)<$len+1)
{
$repeatCount=$len+1-strlen($subStr);
$str=$str."".str_repeat("0",$repeatCount);
}
return $tmpInt."".substr($str,1,1+$len);
}
echo getFloatValue(12.99,4) //12.9900
echo getFloatValue(12.9232555553239,4) //12.9232 相关推荐
weialemon 2019-03-27
PHP100 2019-03-28
beichenyx 2020-06-02
wbczyh 2020-03-28
SJCHEN 2020-02-01
Yasin 2019-12-27
wuxiaosi0 2019-12-16
willowwgx 2019-10-26
socket 2019-04-11
Yellowpython 2019-07-01
jling 2019-07-01
xiaochuachua 2014-02-26
bangrenzhuce 2019-06-25
stoutT 2010-05-18
wuqingyong 2012-12-26
jingxiao 2019-06-21
梦想的翅膀 2012-03-09
花花的技术 2011-11-22