Home > InDesign Scripts > Convert Decimal to Roman and back

## Convert Decimal to Roman and back

Few days ago, on Adobe’s InDesign scripting forum I found something very interesting. It was great little function for number conversion from Decimal to Roman numbers. But it wasn’t I enough so I tried to reverse functionality. Functions are converted to ‘prototypes’ for easier usage. 😀

Decimal to Roman:

```Number.prototype.toRoman = function () {
var romanString = "";
var decimalNumber = this;
var equivalences = {M:1000, CM:900, D:500, CD:400, C:100, XC:90, L:50, XL:40, X:10, IX:9, V:5, IV:4, I:1};
for (var i in equivalences) {
while (decimalNumber >= equivalences[i] ) {
romanString = romanString + i;
decimalNumber = decimalNumber - equivalences[i];
}
}
return romanString;
}
```

Roman to Decimal (keep in mind that you have to pass proper Roman number to get correct result):

```String.prototype.toDecimal = function (){
var c, c1, v, v1, decimalNumber = 0;
var equivalences = {M:1000, CM:900, D:500, CD:400, C:100, XC:90, L:50, XL:40, X:10, IX:9, V:5, IV:4, I:1};
for(var i = 0; i < this.length; i++){
c = this.charAt(i);
v = equivalences[c];
if (i + 1 < this.length){c1 = this.charAt(i + 1);}
v1 = equivalences[c1];
if (v1 > v){decimalNumber += v1 - v;i++;
} else {decimalNumber += v;}
}
return (decimalNumber);
}
```

USAGE

Decimal to Roman:

```var myDecimal = Number(1982);
var myRoman = myDecimal.toRoman(); // returns MCMLXXXII
```

Roman to Decimal:

```var myRoman = String('MCMLXXXII');
var myDecimal = myRoman.toDecimal(); // returns 1982
```

Yeah, easy and effective!

Have fun! 😀

Advertisements
Categories: InDesign Scripts
1. No comments yet.
1. No trackbacks yet.