Page 1 of 1

rounding and padding prices to two decimal digits

Posted: Wed Jan 23, 2008 10:00 pm
by s.dot
I'm about to offer a product sale for a client and I'm having trouble with something so seemingly simple. This is a 25% sale, so the equation goes

Code: Select all

$sale = true;
$salePercent = .25;
 
if ($sale)
{
    $price = round($regPrice - ($price * $salePercent), 2);
} else
{
    $price = $regPrice;
}

echo $salePrice;
Somtimes I get a value like $243.75, nice!
Other times I'll get a rounded value like $7.5 (I want it 7.50)

I was thinking of using str_pad(), but from reading the description it wants a desired length of the input number. Some prices will be over $100 (3 digits) which is a different length than say $10 (2 digits). I'm just concerned with padding the decimal places to ensure that $25 becomes $25.00 and $7.5 becomes $7.50.

I need the extra decimals (even if they're zeros) so it can match prices set in a paypal IPN script.

I could do this with a non-elegant solution of strlen() if(), and str_pad(), but surely there must be an easier way to do this?

Re: rounding and padding prices to two decimal digits

Posted: Wed Jan 23, 2008 10:02 pm
by Kieran Huggins

Re: rounding and padding prices to two decimal digits

Posted: Wed Jan 23, 2008 10:32 pm
by s.dot
Seriously, Kieran. Get over here to Indiana and smack me around a bit in the face. I've used number_format() so many times it's ridiculous. I guess since this is one of my first times dealing with products and money it threw me off a little bit.

smack smack smack

Re: rounding and padding prices to two decimal digits

Posted: Thu Jan 24, 2008 1:04 am
by Kieran Huggins
I sort of figured as much - I have those moments all the time.

I just got back from Philly & NYC, so I'm all road-tripped out for the moment. Will administer a good beating next time I go south 8)