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

将php十进制值四舍五入到最后一个0后的第二位,php,rounding,Php,Rounding,我有一个以十进制值结尾的“动态”计算结果(使用money_格式转换后),如下所示: $cost_per_trans = 0.0000000476 $cost_per_trans = 0.0000007047 货币_格式之前的相应值为: 4.7564687975647E-8 7.0466204408366E-7 这些值的长度可能不同,但我希望能够将它们四舍五入到字符串“0s”后的最后2位,例如: $cost_per_trans = 0.000000048 $cost_per_tra

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

$cost_per_trans  = 0.0000000476 

$cost_per_trans = 0.0000007047
货币_格式之前的相应值为:

4.7564687975647E-8

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

$cost_per_trans = 0.000000048 

$cost_per_trans = 0.00000070
我不确定

  • 如何在正确的位置打球

  • 是在货币格式之前还是之后取整

  • 函数格式\u到\u最后\u 2位($number){
    $depth=0;
    $test=$number;
    而($test<10){/>10意味着我们有足够的深度
    $test=$test*10;
    $depth+=1;
    }
    返回编号\u格式($number,$depth);
    }
    $cost_per_trans=0.0000000476;
    变量转储(格式为最后两位数($cost_per_trans));//0.000000048
    $high_编号=300;
    变量转储(格式为最后两位($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));
    

    您的代码中可能存在错误:第2行将
    $depth
    设置为零,因此它将变得无用。这非常有效,谢谢!但问题是,为什么要使用“$high_number”值?以表明它适用于任何数字,即使是已经有2个以上小数的数字@silkfire的regexp解决方案不起作用。谢谢silkfire。不过,出于某些原因,如果我尝试只使用“$rounded_value”,我会得到字符串(11)“00000000.48”,很抱歉我的错误。使用自定义函数适当地调整了代码。请注意,输入的数字必须是浮点,而不是字符串。
    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));