Price without decimals unless necessary


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.