skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search