
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
JavaScript algorithm for converting Roman numbers to decimal numbers
We are required to write a function that takes in a string of roman number and returns its decimal (base 10) equivalent. Therefore, let’s write the code for this function −
Example
const romanToInt = (s) => { const legend = "IVXLCDM"; const l=[1,5,10,50,100,500,1000]; let sum=0; while(s){ if(!!s[1] && legend.indexOf(s[0]) < legend.indexOf(s[1])){ sum += (l[legend.indexOf(s[1])] - l[legend.indexOf(s[0])]); s = s.substring(2, s.length); } else { sum += l[legend.indexOf(s[0])]; s = s.substring(1, s.length); } } return sum; }; console.log(romanToInt('CLXXVIII')); console.log(romanToInt('LXXXIX')); console.log(romanToInt('LV')); console.log(romanToInt('MDLV'));
Output
The output in the console will be −
178 89 55 1555
- Related Articles
- JavaScript algorithm for converting integers to roman numbers
- C program to convert roman numbers to decimal numbers
- Converting numbers to Indian currency using JavaScript
- Converting strings to numbers with vanilla JavaScript
- JavaScript program to convert positive integers to roman numbers
- Converting Roman Numerals to Decimal lying between 1 to 3999 in C++
- Converting numbers to base-7 representation in JavaScript
- Converting Decimal Number lying between 1 to 3999 to Roman Numerals in C++
- How to validate decimal numbers in JavaScript?
- Algorithm for sorting array of numbers into sets in JavaScript
- How to write 5000 in Roman Numbers?
- Converting array of Numbers to cumulative sum array in JavaScript
- Counting numbers after decimal point in JavaScript
- Converting numbers into corresponding alphabets and characters using JavaScript
- How to convert a decimal number to roman using JavaScript?

Advertisements