Rounding Numbers With PHP

Associate
Joined
6 Feb 2003
Posts
1,105
Location
London
Ive been using PHP's round function to convert floats (prices) to 2d.p. This is all well and good except when its already a number like 100.00 it gets rid of the decimal points and just gives back 100. Is there any way to get it to keep the .00 at the end of these whole numbers?
 
Cuchulain said:
Am I being thick? so for example, you'd round down £54.55 to £54, why would you want to keep the decimal places on £100.00?
wouldnt you round 54.55 UP to 55?
 
Well I have used this in the past, not sure if it is what your looking for:

Code:
$price = round($price, 2);
$temp = explode(".", $price);
if (strlen($temp[1]) == 0) { $price .= ".00"; }
if (strlen($temp[1]) == 1) { $price .= "0"; }
 
I'm assuming you want to keep the zeros for output purposes? If not, then there's no need, as 100 is obviously exactly the same as 100.00, and so the extra decimal places are meaningless from a mathematical point of view.

If you just want to keep the zeros for when you print the number, then just use number_format.
 
Last edited:
yea its purely for outputting purposes. I realise its the same number. I tried that number format thing, didnt have much luck with it though, just kept coming up blank :(
 
Back
Top Bottom