执行圆函数而不使用php中的round()

时间:2012-09-06 06:45:43

标签: php

不使用round()函数在php中执行round()

  $a = "123.45785";
  $v = round($a);
  output: 123.46;

它是通过round函数完成的,但我想在不使用round和number_format()函数的情况下获得输出。

2 个答案:

答案 0 :(得分:1)

以下是使用算术的方法:

function my_round($num, $places = 2) {
  // Multiply to "move" decimals to the integer part                                  
  // (Save one extra digit for rounding)                                              
  $num *= pow(10, $places + 1);
  // Truncate to remove decimal part                                            
  $num = (int) $num;

  // Do rounding based on the last digit                                        
  $lastDigit = $num % 10;
  if ($lastDigit >= 5)
    $num += 10;

  // Remove last digit                                                          
  $num = (int) ($num/10);
  // "Move" decimals in place, and you're done                                  
  $num /= pow(10, $places);
  return $num;
}

答案 1 :(得分:0)

您有sprintf

$a = "123.45785";
echo sprintf("%01.2f", $a); // output: 123.46