Home > Backend Development > PHP Tutorial > Summary of PHP rounding and interception methods of floating point strings

Summary of PHP rounding and interception methods of floating point strings

高洛峰
Release: 2023-03-04 15:18:02
Original
1771 people have browsed it

In phpInterception of floating point typeThere are roughly the following methods:

1. float round (float $val [, int $precision]) returns val according to the specified precision precision (the number of decimal digits after the decimal point) rounded. precision can also be negative or zero (default).

echo round(4.3) //4

2. string sprintf ( string $format [, mixed $args [, mixed $... ]] ) returns the 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位
Copy after login

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
Copy after login

The above are automatically rounded, and sometimes rounding is not required. , what should I do? I haven’t thought of a good solution. If anyone knows, can you 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
Copy after login

For more PHP float interception of floating-point string methods without rounding and related articles, please pay attention to the PHP Chinese website!

Related articles:

php data processing rounding

detailed introduction to the rounding function in php

3 ways to implement rounding in PHP

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template