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?
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)
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:
PHP_ROUND_HALF_UP
- default
PHP_ROUND_HALF_EVEN
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With