# Converting decimal numbers to Roman numerals in JavaScript

Recently I decided to provide all the copyright dates on my sites in Roman numerals rather than decimal, just for something different. It’s not a major change I know, but it was something I wanted to do.

First of all I had to find out how the conversions were actually made. I went to Google, that all important source of information, and found an existing solution written in Java. I quickly converted this to JavaScript, and it is the current script running on the majority of my websites. This simple code is shown below:

However, it is limited to numbers under 4000, which is fine for years, but what about numbers higher than this?

A quick look at the Wikipedia article on Roman numerals will reveal that numbers in thousands are usually written with a bar over the base numeral, or with rounded brackets placed around it. I prefer the bar method so this is what I am going to implement (as you will see however, changing it to use rounded brackets is very easy).

Both the `roman`

and `decimal`

arrays defined in the sample code above will be re-used. So assume that these have been defined as above. Next, I took the code within the `for`

loop in the above sample and put it into its own function, with some additional information:

As you can see, it now also counts the “number of thousands” i.e. the number of times that an ‘M’ is inserted into the `romanNumeral`

variable. This is then returned in an object with the generated Roman numeral.

I then created the `decimalToRoman()`

function which uses the above function to generate the required numeral:

This generates the Roman numeral and then checks to see if the number of thousands is 4 or more. If so, it then replaces the “thousand String” (a list of Ms) with the appropriate base number contained in a span with a CSS styled top border of 1px. This is where you can change the top border to use brackets if you so wish, by setting: `thBase = "(" + thousandsO.romanNumeral + ")";`

.

I have created a Roman numeral test page where you can see it in action for yourself.

Any thoughts and comments, as always, greatly appreciated!

## 6 Responses

Pingback: Tweets that mention Converting decimal numbers to Roman numerals in JavaScript - iandevlin.com – blog -- Topsy.com

I demand a PHP version!

Pfft….easily done though I’m sure.

Pingback: This blog is now HTML5 compliant - iandevlin.com – blog

Pingback: Decimal to Roman Numeral converter ported to PHP - iandevlin.com – blog

Pingback: CONVERTING FROM NUMBERS TO ROMAN NUMERALS IN JAVASCRIPT | talksoftwaretome