title: Truncate float numbers with PHP
body: <p>When a float number needs to be truncated to a certain digit after the floating point, it turns out that it is not easy to be done. For example if the truncating has to be done to second digit after the point, the numbers should be <br></p>
  
  <pre><code>45.8976 =&gt; 45.89, 0.0185 =&gt; 0.01
  </code></pre>
  
  <p>( second digit after the point is not rounded according to the third digit after the point ).</p>
  
  <p>Functions like <code>round()</code>, <code>number_format()</code>, <code>sprintf()</code> round the number and print out</p>
  
  <pre><code>45.8976 =&gt; 45.90, 0.0185 =&gt; 0.02
  </code></pre>
  
  <p>I have met two solutions and I am wondering if they are good enough and which one is better to be used</p>
  
  <p>1.</p>
  
  <pre class="lang-php prettyprint-override"><code>function truncNumber( $number, $prec = 2 )
  {
      return bccomp( $number, 0, 10 ) == 0 ? $number : round( $number - pow( 0.1, bcadd(   $prec, 1 ) ) * 5, $prec );
  }
  </code></pre>
  
  <p>2.</p>
  
  <pre class="lang-php prettyprint-override"><code>function truncNumber($number, $prec = 2 )
  {
      return sprintf( "%.".$prec."f", floor( $number*pow( 10, $prec ) )/pow( 10, $prec ) );
  }
  </code></pre>