0

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!

Olivier
  • 13,283
  • 1
  • 8
  • 24
  • 3
    BTW, you're missing ``$`` symbol before variables ``num1`` and ``num2``. Also, add an example test case showing your issue, how it's different in both of the code. – OMi Shah Aug 26 '23 at 06:37
  • 1
    Can you include the two numbers for which the result is different? How big is the difference? – knittl Aug 26 '23 at 06:49
  • Does this answer your question? [number\_format() in php vs toFixed() in jQuery for validation](https://stackoverflow.com/questions/48901999/number-format-in-php-vs-tofixed-in-jquery-for-validation) – Fraser Aug 26 '23 at 07:40
  • This is not working code. The PHP code is missing `$` before variable names and closes the parentheses of `number_format` before `, 2`. The JavaScript code `float(num1)` produces error message “Can't find variable: float”. Show actual code, with actual numbers, so that people can diagnose the issue. For example, you might be using different floating-point formats in JavaScript and PHP. Edit the question to provide a [mre]. – Eric Postpischil Aug 26 '23 at 11:44

2 Answers2

0

I found an example that shows a difference:

JS:

10.045.toFixed(2)

Result:

10.04

PHP:

echo number_format(10.045, 2);

Result:

10.05

However, this PHP code gives the expected result:

echo sprintf('%.2f', 10.045);

Result:

10.04

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.

Olivier
  • 13,283
  • 1
  • 8
  • 24
-1

maybe this function from this question help you:
How to make number_format() not to round numbers up

function numberFormatPrecision($number, $precision = 2, $separator = '.')
{
    $numberParts = explode($separator, $number);
    $response = $numberParts[0];
    if (count($numberParts)>1 && $precision > 0) {
        $response .= $separator;
        $response .= substr($numberParts[1], 0, $precision);
    }
    return $response;
}
FaramarzDev
  • 19
  • 1
  • 8