Ryan Dawson
Ryan Dawson

Reputation: 21

Getting answer to 2 decimal places in php

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>

Upvotes: 1

Views: 6978

Answers (6)

Bhavya Vaidya
Bhavya Vaidya

Reputation: 1

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

Upvotes: 0

Rohan Khude
Rohan Khude

Reputation: 4913

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);

Upvotes: 0

Orangepill
Orangepill

Reputation: 24665

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);

Upvotes: 5

tomascapek
tomascapek

Reputation: 881

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

Upvotes: 0

Jasbir Singh Sohanpal
Jasbir Singh Sohanpal

Reputation: 181

use echo number_format("2.5",2);

Upvotes: 0

ted
ted

Reputation: 14774

You can try this :

$Total = number_format((float)$number, 2, '.', '');

Upvotes: 0

Related Questions