我有一个“动态”计算的结果,以十进制值结尾(使用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
我不确定
如何在正确的位置进行回合?
是否在money_format之前或之后舍入?
答案 0 :(得分: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
答案 1 :(得分: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));