Posted By

jmiller on 02/21/10


Tagged

number strip price decimals


Versions (?)

Price without decimals unless necessary


 / Published in: PHP
 

Will strip off the decimals of a number (price) unless they are necessary.

  1. <?php
  2. // price(15) returns $15
  3. // price(14.95) returns $14.95
  4.  
  5. function price($price, $decimals=null, $sign='$') {
  6. $price = (float) str_replace($sign, '', $price); // Make sure price is float
  7.  
  8. if ($decimals !== null) {
  9. if (is_numeric($decimals)) {
  10. return $sign.number_format($price, $decimals);
  11. } else {
  12. return $sign.number_format($price, 2);
  13. }
  14. }
  15.  
  16. if (round($price) == $price) {
  17. return $sign.$price;
  18. } else {
  19. return $sign.number_format($price,2);
  20. }
  21. }
  22. ?>

Report this snippet  

You need to login to post a comment.