php float不四舍五入截取浮點型字符串方法總結
更新時間:2013年10月28日 10:02:04 作者:
在php中截取浮點型大致有以下幾種方法。需要的朋友可以過來參考下,希望對大家有所幫助
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
相關文章
PHP簡單實現HTTP和HTTPS跨域共享session解決辦法
這篇文章主要介紹了PHP簡單實現HTTP和HTTPS跨域共享session解決辦法,本文講解的方法相對簡單,需要的朋友可以參考下2015-05-05
CodeIgniter配置之config.php用法實例分析
這篇文章主要介紹了CodeIgniter配置之config.php用法,結合實例形式詳細的分析了CodeIgniter中配置文件config.php的參數含義及具體使用技巧,需要的朋友可以參考下2016-01-01

