1

I am adding 2 prices together (which are session variables) in php and I want it to show 2 decimal places. The session variables themselves show as 2 decimal places but when added together and for example the result is 2.50 only 2.5 is displayed. Is their a way I can display the two decimal places? This is the code I am using

 <div id="info">
  <span class="bluetext2">Total:&nbsp;</span>$<?php echo $_SESSION['startingPrice'] + $_SESSION['postage']; ?><br>
 </div>
bisko
  • 3,948
  • 1
  • 27
  • 29
Ryan Dawson
  • 21
  • 1
  • 2
  • possible duplicate of [How do I format numbers to have only two decimal places?](http://stackoverflow.com/questions/1992406/how-do-i-format-numbers-to-have-only-two-decimal-places) – DFayet Aug 07 '15 at 06:21
  • possible duplicate of [PHP: show a number to 2 decimal places](http://stackoverflow.com/questions/4483540/php-show-a-number-to-2-decimal-places) – l'L'l Aug 07 '15 at 06:23

6 Answers6

4

You have a couple of options here.

number_format - will output the decimal places, can also be used to specify a decimal point character as well as a thousands separator.

echo number_format($x, 2);

printf/sprintf - These are identical except that printf output whereas sprintf returns

printf('%.2f', $x);
echo sprintf('%.2f', $x);

money_format - Locale aware money formater, will use the proper decimal and thousands separators based on locale.

setlocale(LC_MONETARY, "en_US");
echo money_format("%i", $x);
Orangepill
  • 24,500
  • 3
  • 42
  • 63
0

You can try this :

$Total = number_format((float)$number, 2, '.', '');
ted
  • 13,596
  • 9
  • 65
  • 107
0

use echo number_format("2.5",2);

0

Use number_format function. This code:

echo number_format(12345.1, 2, ".","");

will give result: 12345.10

Also you can use short version:

number_format(12345.1, 2)

which results in 12,345.10 (I think that is english format ... )

tomascapek
  • 841
  • 1
  • 8
  • 20
0

As simple as - if u store that as an integer like $total=5.5000 at the time of displaying it will display 5.5. If u use is as $total="5.5000" then it will display as 5.5000

OR

$asdf=$x+$y; //5=2.50+2.50 echo number_format($asdf,2);

Rohan Khude
  • 4,455
  • 5
  • 49
  • 47
0

Possible duplicate to PHP: show a number to 2 decimal places

Use number_format((float('number to be rounded off'),' number of decimal places to be rounded off','separator between the whole number and the number after the separator')

example

$foo = 150
echo number_format(float($foo),2,'.')

will give 150.00

Community
  • 1
  • 1