How to convert an integer value to a Roman Numeral representation #101

Converts an integer value to a string containing a roman numeric code ("XVII"):

{
Parameters:   Num: Integer to convert.
Return Value: Roman numerical representation of the passed integer value.
History:      12/7/99 "Philippe Ranger"
}
function IntToRoman(num: Cardinal): string;
const
  Nvals = 13;
  vals: array [1..Nvals] of word =
    (1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000);
  roms: array [1..Nvals] of string[2] =
    ('I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C',
    'CD', 'D', 'CM', 'M');
var
  b: 1..Nvals;
begin
  result := '';
  b := Nvals;
  while num > 0 do
  begin
    while vals[b] > num do
      dec(b);
    dec (num, vals[b]);
    result := result + roms[b]
  end;
end;

Demo code

A ready made project containing this demo code is available. View the project.

This demo displays the roman numerals up to 3999, which is about as large a number as this routine can cope with. To create the demo start a new Delphi VCL application then:

  • Drop a TListBox on the form. Set its TabWidth property to 30.
  • Create an OnCreate event handler for the form.
  • Name the form "Form1" and save the form unit as Unit1.pas.
  • Now code Unit1 as follows:
unit Unit1;

interface

uses
  SysUtils, Forms, Classes, Controls, StdCtrls;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    procedure FormCreate(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function IntToRoman(num: Cardinal): string;
const
  Nvals = 13;
  vals: array [1..Nvals] of word =
    (1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000);
  roms: array [1..Nvals] of string[2] =
    ('I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C',
    'CD', 'D', 'CM', 'M');
var
  b: 1..Nvals;
begin
  result := '';
  b := Nvals;
  while num > 0 do
  begin
    while vals[b] > num do
      dec(b);
    dec (num, vals[b]);
    result := result + roms[b]
  end;
end;

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
var
  N: Cardinal;
  R: string;
begin
  for N := 1 to 3999 do
  begin
    R := IntToRoman(N);
    ListBox1.Items.Add(Format('%d'#9'%s', [N, R]));
  end;
end;

end.

Run the program. When it appears all the integers from 1 to 3999 are displayed in the list box as digits and as roman numbers.

Demo by Peter Johnson

Original resource: The Delphi Pool
Author: Philippe Ranger
Added: 2009/09/14
Last updated: 2010/03/16