将PHP十进制值四舍五入到最后一个0后的第二位


round php decimal value to second digit after last 0

我有一个"on the fly"计算的结果,以十进制值结束(使用money_format转换后),如下所示:

$cost_per_trans  = 0.0000000476 
$cost_per_trans = 0.0000007047

money_format前对应的值为:

4.7564687975647E-8
7.0466204408366E-7

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

$cost_per_trans = 0.000000048 
$cost_per_trans = 0.00000070

我不确定

  1. 如何在正确的位置做轮?

  2. 是否在money_format之前或之后舍入?

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

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

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