Jump to content

Alter function to format negative number


Scooby08

Recommended Posts

How would I go about altering this function to format a negative number?

 

<?php
function show_price($price) { 
$price = round(100*$price)/100;
if (round($price*10) == $price*10 && round($price)!=$price) 
	$price = "$price"."0";
if (round($price) == $price) 
	$price = "$price".".00";

return "$".number_format($price,2);
}
?>

 

Right now the negative number formats like so:

 

$-99.99

 

and I'm looking to format it like so:

 

-$99.99

 

Can anybody help me out??

 

 

function show_price($price) {
$format = '$%0.2f';
if($price < 0) {
	$price = -$price;
	$format = "-$format";
}
return sprintf($format, $price);
}

 

Your current function could just be done

sprintf('$%0.2f', $price);

 

sprintf/printf are your friends!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.