toRoman method
Converts the integer to Roman numerals Supports numbers from 1 to 3999 Extension to convert integers to Roman numerals Converts the integer to Roman numerals Supports numbers from 1 to 3999
Implementation
String toRoman() {
if (this < 1) {
return '';
}
if (this > 3999) {
throw RangeError.range(
this, 1, 3999, 'toRoman', 'Value must be between 1 and 3999');
}
// Roman numeral mapping in descending order
const romanNumerals = <int, String>{
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();
// Convert the number to Roman numerals
for (final entry in romanNumerals.entries) {
final value = entry.key;
final numeral = entry.value;
// Append the numeral while reducing the number
final count = number ~/ value;
if (count > 0) {
result.write(numeral * count);
number %= value;
}
}
return result.toString();
}