0

我有一个以十进制值结尾的“动态”计算结果(使用money_format转换后),如下所示:

$cost_per_trans  = 0.0000000476 

$cost_per_trans = 0.0000007047

money_format 之前的对应值为:

4.7564687975647E-8

7.0466204408366E-7

这些值可能具有不同的长度,但我希望能够将它们四舍五入到“0s”字符串之后的最后 2 位数字,例如:

$cost_per_trans = 0.000000048 

$cost_per_trans = 0.00000070

我不确定

  1. 如何在正确的位置进行回合?

  2. 是在money_format之前还是之后舍入?

4

2 回答 2

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
于 2013-05-22T16:38:57.617 回答
0

您的舍入方法非常具体。试试这个:

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));
于 2013-05-22T16:44:57.180 回答