Search code examples
phpstringfloating-pointnumber-formatting

Print result of subtraction involving floating point numbers to two decimals


I have 3 strings as 3 variables: $amount1, $amount2, $amount3.

Both, $amount2 and $amount3 have values after decimal points like 12.34 or 12.00

Now I am performing following operation like

$amount1 = $amount1 - ($amount2 + $amount3);

I need to display value of $amount, with decimal points even if it is not needed.

example:

$amount1     =         $amount1      -     ($amount2 + $amount3)
  12                       20               (6.00 + 2.00)
  

In above example, I am getting 12, but I need to display as 12.00


Solution

  • $amount1 = $amount1 - ($amount2 + $amount3);
    echo number_format($amount1, 2, '.', '');
    // Echos 12.00
    

    Link to PHP Docs: http://php.net/manual/en/function.number-format.php

    If you are dealing with monetary values, you can use money_format method too.