PHP ROUND vs Javascript ROUND

后端 未结 5 1006
花落未央
花落未央 2021-01-13 16:12

I found a very strange issue, the issue is the ROUND method in PHP and Javascript the calculation results are not the same!?

See the following example:

PHP

相关标签:
5条回答
  • To control it more use ceil and floor for rounding. That way you can choose which way to round

    0 讨论(0)
  • 2021-01-13 16:34
    console.log(Math.round(175.5)); // 176
    console.log(Math.round(-175.5)); // -175 <-why not -176!!??
    

    175.5 its round value 176 it's value increasing.

    -175.5 round value is -175. Because when I round -175.5 then it also increasing that means -175>-176.

    0 讨论(0)
  • 2021-01-13 16:41

    That's not an issue, it is well documented

    If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. Note that this differs from many languages' round() functions, which often round this case to the next integer away from zero, instead (giving a different result in the case of negative numbers with a fractional part of exactly 0.5).

    If you want the same behaviour on Javascript, I would use

    var n = -175.5;
    var round = Math.round(Math.abs(n))*(-1)
    
    0 讨论(0)
  • 2021-01-13 16:52

    Or... if you wanted JavaScript to behave the same as PHP, use this:

    function phpRound(number) {
      if(number < 0)
        return 0 - Math.round(0 - number);
      return Math.round(number);
    }
    
    0 讨论(0)
  • 2021-01-13 16:53

    A quick solution is to do the following:

    echo round(-175.5, 0, PHP_ROUND_HALF_DOWN); // -175
    

    There are other modes to choose from:

    1. PHP_ROUND_HALF_UP - default
    2. PHP_ROUND_HALF_EVEN
    3. PHP_ROUND_HALF_ODD

    See the documentation for more information.

    This function will behave the same as in javascript:

    function jsround($float, $precision = 0){
      if($float < 0){
         return round($float, $precision, PHP_ROUND_HALF_DOWN);
      }
    
      return round($float, $precision);
    }
    
    0 讨论(0)
提交回复
热议问题