fork download
  1. <?php
  2.  
  3. class NumberQuantifier {
  4. protected $quantifierList;
  5.  
  6. public function __construct($quantifierList) {
  7. $this->quantifierList = $quantifierList;
  8. arsort($this->quantifierList);
  9. }
  10.  
  11. public function quantify($number) {
  12. foreach ($this->quantifierList as $symbol => $threshold) {
  13. if ($threshold > $number) continue;
  14.  
  15. return number_format($number / $threshold, 1) . $symbol;
  16. }
  17. }
  18. }
  19.  
  20. $metricMassQuantifier = new NumberQuantifier(array(
  21. 'Mg' => 1000000, //megagram
  22. 'kg' => 1000, //kilogram
  23. 'hg' => 100, //hectogram
  24. 'dag' => 10, //decagram
  25. 'g' => 1, //gram
  26. 'dg' => 1/10, //decigram
  27. 'cg' => 1/100, //centigram
  28. 'mg' => 1/1000, //millgram
  29. 'mcg' => 1/10000000 //microgram
  30. ));
  31.  
  32. $imperialMassQuantifier = new NumberQuantifier(array(
  33. 'gr' => 1/7000, //grain
  34. 'dr' => 1/256, //drachm
  35. 'oz' => 1/16, //ounce
  36. 'lb' => 1, //pound
  37. 'st' => 14, //stone
  38. 'qtr' => 28, //quarter
  39. 'cwt' => 112, //hundredweight
  40. 't' => 2240 //ton
  41. ));
  42.  
  43. echo "Metric: {$metricMassQuantifier->quantify(456)} \r\n";
  44. echo "Imperial: {$imperialMassQuantifier->quantify(456)} \r\n";
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
Metric: 4.6hg 
Imperial: 4.1cwt