Home > Article > Backend Development > php float method to intercept floating point string without rounding
There are roughly the following methods to intercept floating point types in php. Friends in need can come here for reference, I hope it will be helpful to everyone
There are roughly the following methods to intercept floating point types in php:
1, float round ( float $val [, int $precision ] ) returns the result of rounding val according to the specified precision (the number of decimal digits after the decimal point). precision can also be negative or zero (default).
echo round(4.3) //4
2、 string sprintf ( string $format [, mixed $args [, mixed $... ]] ) return String of formatted data
$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
All of the above Automatic rounding is done. Sometimes rounding is not required. What should I do? I haven’t thought of a good way. Who knows can tell me.
I wrote a troublesome function and recorded it
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
The above is the entire content of this article. I hope it will be helpful to everyone’s study. More related content Please pay attention to PHP Chinese website!
Related recommendations:
Introduction to php using parse_url and parse_str to parse URLs
##PHP full-featured non-deformation image cropping Introduction to operation classes and usage
The above is the detailed content of php float method to intercept floating point string without rounding. For more information, please follow other related articles on the PHP Chinese website!