NumberHelper.php 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace fphammerle\helpers;
  3. class NumberHelper
  4. {
  5. static $roman_symbols = [
  6. 'M' => 1000,
  7. 'CM' => 900,
  8. 'D' => 500,
  9. 'CD' => 400,
  10. 'C' => 100,
  11. 'XC' => 90,
  12. 'L' => 50,
  13. 'XL' => 40,
  14. 'X' => 10,
  15. 'IX' => 9,
  16. 'V' => 5,
  17. 'IV' => 4,
  18. 'I' => 1,
  19. ];
  20. /**
  21. * @return string|null
  22. */
  23. public static function formatRoman($number)
  24. {
  25. if($number === null) {
  26. return null;
  27. }
  28. if(!is_int($number)) {
  29. throw new \InvalidArgumentException('expected integer');
  30. }
  31. $roman_number = '';
  32. while($number > 0) {
  33. foreach(self::$roman_symbols as $roman_digit => $roman_digit_value) {
  34. if($number >= $roman_digit_value) {
  35. $roman_number .= $roman_digit;
  36. $number -= $roman_digit_value;
  37. break;
  38. }
  39. }
  40. }
  41. return $roman_number;
  42. }
  43. }