This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET 1.1+

# Convert a Number into Roman Numerals

Roman numerals are an ancient number system but still have uses in the modern world. Roman numerals are used to represent dates, adorn clock faces and for indexing. This article describes an algorithm and C# code to convert a number into Roman numerals.

### Initialising the Resultant String

The resultant string will be built up in stages using a StringBuilder object as this is efficient for the recursive appending that will occur. To initialise the StringBuilder, add the following code:

```// Initialise the string builder
StringBuilder result = new StringBuilder();```

### Building the Roman Numerals

Now that all of the data has been initialised, the process of appending letters and pairs to the StringBuilder must be developed. This simple process loops through all of the items in the integer array, starting with the largest value. If the number found in the array is as large or larger than the number being converted then the corresponding letter or pair or letters from the numerals array is appended to the StringBuilder.

Each time the StringBuilder is updated, the number being converted is decreased by the appended letter or pair's value. This stops numerals from being incorrectly appended and ensures that the loop does not become infinite. The iterative process continues until all of the values in the integer array have been processed and the number being converted has therefore been reduced to zero.

The code for the loop is as follows:

```// Loop through each of the values to diminish the number
for (int i = 0; i < 13; i++)
{
// If the number being converted is less than the test value, append
// the corresponding numeral or numeral pair to the resultant string
while (number >= values[i])
{
number -= values[i];
result.Append(numerals[i]);
}
}```

### Completing the Method

All that remains now is to convert the StringBuilder value into a string so that it can be returned to the calling routine. Add the final code and you are ready to test the method.

```// Done
return result.ToString();```

### Reversing the Conversion

An algorithm to reverse the operation by converting roman numerals to an integer value can be found in the article, Convert Roman Numerals into Numbers.

4 October 2007