round php decimal value to second digit after last 0

允我心安 提交于 2019-12-25 07:01:06

问题


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?


回答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



回答2:


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));


来源:https://stackoverflow.com/questions/16697190/round-php-decimal-value-to-second-digit-after-last-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!