General
This script will convert whole numbers to Roman numerals, up to 3,999,999. Easy to use.
Notes
- Created by: Kurt Grigg
- Web Site: http://www.kurtsdhtml.pwp.blueyonder.co.uk/
Source Code
Paste this source code into the designated areas.
External file
Paste this code into an external JavaScript file named: romanNumerals.js
function isValidInput(x){
var inpt = document.getElementById(“converterinput”);
if (x == “” || /^s+$/.test(x)){
alert(‘Empty!nEnter a number to be converted to Roman numerals.’);
inpt.value = “”;
inpt.focus();
return false;
}
x = x.replace(/[ ]+/g,””);
inpt.value = x;
if (/D+/g.test(x)){
alert(“Numbers only!nRemoving non-numerical characters…”);
x = x.replace(/D+/g,””);
inpt.value = x;
if (x == “”) {
alert(‘…no number found after removal.nTry again.’);
inpt.focus();
return false;
}
}
if (/^0+$/g.test(x)){
inpt.value = 0;
inpt.select();
alert(‘There is no Roman numeral for zero!nEnter a number from 1 to 3,999,999’);
return false;
}
if (x < 1 || x > 3999999){
x = x.replace(/^0+/g,””);
inpt.value = x;
alert(‘Enter a number from 1 to 3,999,999 only!’);
inpt.select();
return false;
}
x = x.replace(/^0+/g,””);
inpt.value = x;
converter(x);
}
function drawNumerals(n){
var d = document;
var temp = d.getElementById(‘converteroutput’);
temp.firstChild.data = ”;
var draw = d.createElement(‘span’);
if (n.toLowerCase() == n){
draw.style.borderTop = ‘2px solid #000000’;
draw.style.fontVariant = ‘small-caps’;
}
draw.appendChild(d.createTextNode(n));
temp.appendChild(draw);
}
function converter(e){
var t = drawNumerals;
var a = [[1000000,’m’],
[900000,’cm’],[500000,’d’],[400000,’cd’],[100000,’c’],
[90000,’xc’],[50000,’l’],[40000,’xl’],[10000,’x’],
[9000,’M’,’x’],[5000,’v’],[4000,’M’,’v’],[1000,’M’],
[900,’CM’],[500,’D’],[400,’CD’],[100,’C’],
[90,’XC’],[50,’L’],[40,’XL’],[10,’X’],
[9,’IX’],[5,’V’],[4,’IV’],[1,’I’]];
for (var i = 0; i < a.length; i++){
while (e – a[i][0] >= 0){
t(a[i][1]);
if (a[i].length == 3){
t(a[i][2]);
}
e -= a[i][0];
}
}
}
function resetconverter(){
var temp = document.getElementById(“converteroutput”);
while (temp.lastChild.nodeName == ‘SPAN’){
temp.removeChild(temp.lastChild);
}
document.getElementById(“converterinput”).value = “”;
}
function beginConverter(e){
resetconverter();
isValidInput(e);
}
Head
Paste this code into the HEAD
section of your HTML document.
<script type=”text/javascript” src=”romanNumerals.js”></script>
Body
Paste this code into the BODY
section of your HTML document.
<div id=”convertercontainer”>
<div id=”convertertitle”>Numbers To Roman Numerals Converter</div>
Enter a number from 1 to 3,999,999<br>
<input type=”text” id=”converterinput” value=”” autocomplete=”off”> = <span id=”converteroutput”> </span><br>
<input class=”converterbuttons” type=”button” value=”Convert” onclick=”beginConverter(document.getElementById(‘converterinput’).value);this.blur()”>
<input class=”converterbuttons” type=”button” value=”Reset” onclick=”resetconverter();this.blur()”>
</div>