roman property

String get roman

Returns the Roman numeral representation of an integer from 1 to 3999

print(12.roman);   // XII
print(455.roman);  // CDLV
print(1.roman);    // I
print(3999.roman); // MMMCMXCIX

Implementation

String get roman {
  if (this < 1 || this > 3999) {
    throw ArgumentError('Number out of range (1 to 3999)');
  }

  final romanMap = {
    1000: 'M',
    900: 'CM',
    500: 'D',
    400: 'CD',
    100: 'C',
    90: 'XC',
    50: 'L',
    40: 'XL',
    10: 'X',
    9: 'IX',
    5: 'V',
    4: 'IV',
    1: 'I',
  };

  var num = this;
  final buffer = StringBuffer();

  for (final entry in romanMap.entries) {
    while (num >= entry.key) {
      buffer.write(entry.value);
      num -= entry.key;
    }
  }

  return buffer.toString();
}