简体   繁体   中英

perform round function without using round() in php

without use of round() function perfrom the round() in php

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

it had done by round function but i want to get output without use of round and number_format() function.

Here's a way of doing it with arithmetics:

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

You have sprintf .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM