Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Roman Numerals

1. ## Roman Numerals

Easy Roman numerals based on the additional set of rules found at
http://en.wikipedia.org/wiki/Roman_numerals

Code:
```var roman = (function(){
function roman(n){
var d=[3000,2000,1000,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1]
var r=["MMM","MM","M","CM","DCCC","DCC","DC","D","CD","CCC","CC","C","XC","LXXX","LXX","LX","L","XL","XXX","XX","X","IX","VIII","VII","VI","V","IV","III","II","I"]
rs=""
for(var i=0;i<d.length;i++){
if(n>=d[i]){
rs+=r[i];
n-=d[i];
}
}
return rs;
}
return {
num:function(n){return roman(n);}
};
})();
alert(roman.num(1984))```
Only for use in the numeric range of 1 to 3999

• Nice.
But there is a typo.
You have defined the roman for 100 to be "CC"

• This version allows for both the original and more recent versions of Roman numberals (the original allowed the values in any order and used up to 4 of each symbol while the more recent version required the symbols to be in descending order with reversals indicating subtraction). If no value is passed as a parameter it returns the original version of the corresponding Roman numberal while passing true into the call uses replace statements to swap any occurrence of 4 of the same symbol for the more modern equivalent.

Code:
```Number.prototype.toRoman = function(s) {
var n, d, r, rn, x, i;
n = Math.floor(this);
if (n < 1 || n > 3999) throw new RangeError(this + ' cannot be converted to Roman Numberals');
r = '';
rn = ['IIII','V','XXXX','L','CCCC','D','MMMM'];
for (i = 0; i < rn.length; i++) {
x = rn[i].length+1;
d = n%x;
r= rn[i].substr(0,d)+r;
n = (n-d)/x;
}
if (s) {
r=r.replace(/DCCCC/g,'CM');
r=r.replace(/CCCC/g,'CD');
r=r.replace(/LXXXX/g,'XC');
r=r.replace(/XXXX/g,'XL');
r=r.replace(/VIIII/g,'IX');
r=r.replace(/IIII/g,'IV');
}
return r;
}```

• here's a refactoring of the original function. Taking felgall's lead, extended Number and added error generation.

Code:
```Number.prototype.toRoman=function(){
for(
var i=(this<1||this>3999||this!=Math.floor(this))?(function(){throw new Error('Number is not a whole number or not in range [1,3999]')})():0,
s="",
n=this,
d=3000,
r=["MMM","MM","M","CM","DCCC","DCC","DC","D","CD","CCC","CC","C","XC","LXXX","LXX","LX","L","XL","XXX","XX","X","IX","VIII","VII","VI","V","IV","III","II","I"],
l=r.length;
i<l;
s+=(n>=d)?(function(){n-=d;return r[i]})():"",
d-=(i<2)?1000:(i<11)?100:(i<20)?10:1,
i++
){}
return s;
}

alert((1945).toRoman());
try{alert((19.45).toRoman())}catch(e){alert(e.message)};```

• See:- Regular expression help (author: Old Pedant) for a script to convert Roman Numbers to text.

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•