简体   繁体   English

执行回合函数而不在PHP中使用round()

[英]perform round function without using round() in php

without use of round() function perfrom the round() in php 不使用round()函数perfrom在PHP中的round()

  $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. 它已经通过回合函数完成,但我想在不使用回合和number_format()函数的情况下获得输出。

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 . 你有sprintf

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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