I-M-JM
I-M-JM

Reputation: 15960

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

Upvotes: 1

Views: 72

Answers (2)

Felix Kling
Felix Kling

Reputation: 817228

Or (s)printf

printf('%.2f', 20 - (6.00 + 2.00));

Upvotes: 0

Greg
Greg

Reputation: 21909

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

Upvotes: 3

Related Questions