0

I have results of an "on the fly" calculation that end in decimal values (after converted using money_format) as follows:

$cost_per_trans  = 0.0000000476 

$cost_per_trans = 0.0000007047

The corresponding values before the money_format are:

4.7564687975647E-8

7.0466204408366E-7

These values may be of different lengths but I would like to be able to round them to the last 2 digits after the string of "0s", to get this for example:

$cost_per_trans = 0.000000048 

$cost_per_trans = 0.00000070

I am unsure of

  1. how to do the round in the right spot?

  2. whether to round before or after the money_format?

TheHippo
  • 61,720
  • 15
  • 75
  • 100
  • http://www.php.net/manual/en/function.round.php#24379 – Vedran Šego May 22 '13 at 16:40
  • possible duplicate of [Can I rely on PHP php.ini precision workaround for floating point issue](http://stackoverflow.com/questions/14587290/can-i-rely-on-php-php-ini-precision-workaround-for-floating-point-issue) – hek2mgl May 22 '13 at 16:42

2 Answers2

1
function format_to_last_2_digits($number) {
    $depth = 0;
    $test = $number;
    while ($test < 10) {    // >10 means we have enough depth
        $test = $test * 10;
        $depth += 1;
    }
    return number_format($number, $depth);
}

$cost_per_trans = 0.0000000476;
var_dump(format_to_last_2_digits($cost_per_trans)); // 0.000000048
$high_number = 300;
var_dump(format_to_last_2_digits($high_number));    // 300
Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • There is an error in your code: line 2 sets `$depth` to zero, so it becomes useless. – GTF May 22 '13 at 16:47
  • This works perfectly, thank you! Question though, why the "$high_number" value? – bridgemanusa May 22 '13 at 16:56
  • To show that it works for any number, even a number that has more than 2 decimals already. @silkfire's regexp solution wont work. – Halcyon May 22 '13 at 17:01
0

Your rounding method is very specific. Try this:

function exp2dec($number) {
   preg_match('#(.*)E-(.*)#', str_replace('.', '', $number), $matches);
   $num = '0.';

   while ($matches[2] > 1) {
      $num .= '0';
      $matches[2]--;
   }

   return $num . $matches[1];
}


$cost_per_trans = 0.0000000476;

preg_match('#^(0\.0+)([^0]+)$#', exp2dec($cost_per_trans), $parts);

$rounded_value = $parts[1] . str_replace('0.', '', round('0.' . $parts[2], 2));
silkfire
  • 24,585
  • 15
  • 82
  • 105
  • Thanks silkfire. For some reasosn though, if I try to use just "$rounded_value" I get string(11) "00000000.48" – bridgemanusa May 22 '13 at 17:03
  • Sorry my mistake. Adjusted the code appropriately with a custom function. Notice that the input number must be a float, not a string. – silkfire May 22 '13 at 17:07