rounding and padding prices to two decimal digits

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

rounding and padding prices to two decimal digits

Post 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?
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: rounding and padding prices to two decimal digits

Post by Kieran Huggins »

User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: rounding and padding prices to two decimal digits

Post 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
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: rounding and padding prices to two decimal digits

Post 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)
Post Reply