php float unrounded truncation of floating point string method summaries

  • 2020-10-23 20:54:39
  • OfStack

There are several ways to intercept floating point in php:

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

echo round(4.3) //4

2, string sprintf (string $format [, mixed $args [, mixed $...]]) returns a string of formatted data


$a=12.338938438; 
echo sprintf("%.5f",$a) // Results: 12.33894  

$a=12.3312356; 
echo sprintf("%.5f",$a);//12.33124 
echo sprintf("%f",$a);//331236   After the default decimal point 6 position  

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 

So all of these things are done automatically, and sometimes you don't need to round 4 or round 5, so what do you do? You don't have a good idea. Who knows, you can tell me 1.

I wrote a troublesome function, and I wrote it down


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 


Related articles: