PHP ROUND vs Javascript ROUND

I found a very strange problem, the problem is the ROUND method in PHP and Javascript, the calculation results do not match !?

See the following example:

Php

echo round(175.5); // 176
echo round(-175.5); // -176

Javascript

console.log(Math.round(175.5)); // 176
console.log(Math.round(-175.5)); // -175 <-why not -176!!??

Does anyone know why? and how to make Javascript and PHP the same results?

+4
source share
4 answers

This is not a problem, this is well documented

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

Javascript,

var n = -175.5;
var round = Math.round(Math.abs(n))*(-1)
+4

, :

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

:

  • PHP_ROUND_HALF_UP -
  • PHP_ROUND_HALF_EVEN
  • PHP_ROUND_HALF_ODD

. .

, :

function jsround($float, $precision = 0){
  if($float < 0){
     return round($float, $precision, PHP_ROUND_HALF_DOWN);
  }

  return round($float, $precision);
}
+2
console.log(Math.round(175.5)); // 176
console.log(Math.round(-175.5)); // -175 <-why not -176!!??

175.5 176 .

-175.5 - -175. , -175.5, -175 > ​​-176.

+2

, ceil floor . , ,

+1

Source: https://habr.com/ru/post/1672273/


All Articles