Working with Roman Numerals


You need to format numbers as Roman numerals. Perhaps you’ve just written the next Titanic or Star Wars episode and you need to get the copyright date correct. Or, on a more mundane level, you need to format page numbers in the front matter of a book.


Use my RomanNumberFormat class:

RomanNumberFormat nf = new RomanNumberFormat(  );
int year = Calendar.getInstance(  ).get(Calendar.YEAR);
System.out.println(year + " -> " + nf.format(year));

The use of Calendar to get the current year is explained in Section 6.2. Running RomanNumberSimple looks like this:

+ jikes +E -d .
+ java RomanNumberSimple
2000 -> MM


There is nothing in the standard API to format Roman numerals. However, the java.text.Format class is designed to be subclassed for precisely such unanticipated purposes, so I have done just that and developed a class to format numbers as Roman numerals. Here is a better and complete example program of using it to format the current year. I can pass a number of arguments on the command line, including a "-" where I want the year to appear (note that these arguments are normally not quoted; the "-" must be an argument all by itself, just to keep the program simple). I use it as follows:

$ java  RomanYear   Copyright (c) - Ian Darwin
Copyright (c) MMI Ian Darwin

The code for the RomanYear program is simple, yet it correctly gets spaces around the arguments.

import java.util.*; /** ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.