We do two types of decimal and numerical calculations with JS and PHP. And finally, we fix the decimal to the last two digits.
For example:
JS =>
var finalPrice = (float(num1) + float(num2)).toFixed(2);
PHP =>
$finalPrice = number_format((float) (num1 + num2)), 2 );
We round the final numbers obtained from multiplication and division and finally send the result to the backend.
Now, we want to compare these two numbers obtained from JS and PHP if they were exactly the same. For example, send the final number to the gateway.
But this comparison is not done correctly due to the presence of decimal numbers and the rounding algorithm of JS and PHP. What is the solution to this issue?
I expected the results of the calculations to be the same and to be able to compare these two numbers. But this was not happening!
2
Answers
I found an example that shows a difference:
JS:
Result:
PHP:
Result:
However, this PHP code gives the expected result:
Result:
So it looks like
number_format()
uses a different rounding rule and should be avoided if you want a consistent behavior with JS and PHP.maybe this function from this question help you:
How to make number_format() not to round numbers up