toRoman method

String toRoman()

Converts the integer to Roman numerals (supports values from 1 to 3999).

Example:

print(2023.toRoman()); // MMXXIII

Implementation

String toRoman() {
  if (this < 1 || this > 3999) {
    throw RangeError.range(
        this, 1, 3999, 'toRoman', 'Value must be between 1 and 3999');
  }
  const romanNumerals = {
    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 number = this;
  final result = StringBuffer();
  for (final entry in romanNumerals.entries) {
    final count = number ~/ entry.key;
    if (count > 0) {
      result.write(entry.value * count);
      number %= entry.key;
    }
  }
  return result.toString();
}