Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip Price decimals when necessary

This is more of an aesthetic problem, if I were to output two prices in PHP:

(the first being 123.45 and the second being 123.00)

is there a way I can remove the .00 from the second price when necessary (show it only appears as = 123) but have it remain if there are numbers greater than 0 for a price (like the first price?).

Any help would be great, thanks!

TC

like image 246
TronCraze Avatar asked Feb 01 '11 21:02

TronCraze


3 Answers

If you don't want to use (slow) regular expressions, you can use str_replace:

$value = str_replace('.00', '', $value);

note: I'm assuming you don't want to change '123.10' to '123.1', you only want to remove double zeros, right?

like image 81
Francisco R Avatar answered Nov 08 '22 07:11

Francisco R


what about...

$value = preg_replace('~\.0+$~','',$value);
like image 22
Crayon Violent Avatar answered Nov 08 '22 05:11

Crayon Violent


function round2($decimal,$places = 2){
  $decimal = round($decimal,$places);
  if (floor($decimal)==$decimal)
    return (string)floor($decimal);
  return $decimal;
}
echo round2(123.45)."<br />".round2(123.00);

Something like that?

like image 2
Brad Christie Avatar answered Nov 08 '22 05:11

Brad Christie