JavaScript roman numeral converter.

Here's the JavaScript Roman Numeral Conversion functions I alluded to in the last post.

//each numeral, starting with the largest
var numerals = {
function RomanToDecimal(roman) {
//the roman numeral value
var _v = roman.toUpperCase();
//this holds the decimal equivalent
var _d = 0;
//if the roman value contains more than the allowed letters return Not a Number
if (!_v.match(/^[MDCLXVI]+$/)) return NaN;
//for each roman numeral
for (_n in numerals) {
//while this numeral is at the front of the passed string
while (_v.match(new RegExp("^"+_n))) {
//add the numeral's decimal value to the decimal equivalent
_d += numerals[_n];
//and pop off the numeral found
_v = _v.substr(_n.length);
// still letters left. Improper sequencing. return Not a Number
if (_v.length) return NaN;
//otherwise, return the decimal equivalent
else return _d;

function DecimalToRoman(num) {
//the decimal equvalent
var _d = parseInt(num);
//this will hold the roman value
var _r = '';
//for each roman numeral
for(var _n in numerals) {
// get the number of times (if any) it divides into the decimal value
var _x =Math.floor(_d/numerals[_n]);
// if it does divide into the decimal value
if (_x) {
// subtract that amount from the decimal value
_d -= (_x*numerals[_n]);
//and add the appropriate number of numerals to the roman value
for(var a=0;a<_x;a++) {
_r += _n;
// if the decimal value now equals zero, stop building our number
if (!_d) break;
return _r;
Tags: ,
2009.08.17 01:07 PM | Permalink 0 Comments