Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP ROUND vs Javascript ROUND

Tags:

javascript

php

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

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!!??

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

like image 819
Jasper Avatar asked Mar 14 '17 16:03

Jasper


2 Answers

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)
like image 147
DrKey Avatar answered Sep 20 '22 02:09

DrKey


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);
}
like image 33
Xorifelse Avatar answered Sep 18 '22 02:09

Xorifelse