A software engineer bent on world bovine domination. I write code at 99designs.com. By Dennis Hotson.
Nov 01
Permalink

Need to make some numbers look nicer? No worries, fudge them!

   1 <?php
   2 
   3 /**
   4  * Need to make some numbers look nicer? No worries, fudge them!
   5  * @author dennis.hotson@gmail.com <Dennis Hotson>
   6  */
   7 class Fudge
   8 {
   9   /**
  10    * Makes a number look nicer
  11    * @param $n int
  12    *  3 - 30 rounds to the nearest 1
  13    *  30 - 300 rounds to the nearest 10
  14    *  300 - 3000 rounds to the nearest 100
  15    */
  16   public static function round($n)
  17   {
  18     return self::_round($n, self::_accuracy($n));
  19   }
  20 
  21   /**
  22    * Makes a number look like a bargain price
  23    * @param $n int
  24    */
  25   public static function price($n)
  26   {
  27     $accuracy = self::_accuracy($n);
  28 
  29     if (self::_accuracy($n, 3) < self::_accuracy($n, 1))
  30       $adjustment = $accuracy / 10;
  31     else
  32       $adjustment = $accuracy / 20;
  33 
  34     return self::_round($n, self::_accuracy($n)) - $adjustment;
  35   }
  36 
  37   /**
  38    * @param $n int
  39    * @param $offset
  40    * @return int A power of 10 eg 1,10,100....
  41    */
  42   private static function _accuracy($n, $offset = 3)
  43   {
  44     return pow(10, floor(log10(max(1, $n)) - log10($offset)));
  45   }
  46 
  47   /**
  48    * Rounds $n to the nearest $accuracy
  49    */
  50   private static function _round($n, $accuracy)
  51   {
  52     return round($n / $accuracy) * $accuracy;
  53   }
  54 }
Also on github.