xxxxxxxxxx
function toRoman(num) {
// Create an array of Roman numerals and their corresponding decimal values
const romanNumerals = [ { numeral: "M", value: 1000 }, { numeral: "CM", value: 900 }, { numeral: "D", value: 500 }, { numeral: "CD", value: 400 }, { numeral: "C", value: 100 }, { numeral: "XC", value: 90 }, { numeral: "L", value: 50 }, { numeral: "XL", value: 40 }, { numeral: "X", value: 10 }, { numeral: "IX", value: 9 }, { numeral: "V", value: 5 }, { numeral: "IV", value: 4 }, { numeral: "I", value: 1 } ];
let result = "";
// Loop through the array of Roman numerals
for (const romanNumeral of romanNumerals) {
// While the input number is greater than or equal to the value of the current Roman numeral
while (num >= romanNumeral.value) {
// Add the corresponding Roman numeral to the result string
result += romanNumeral.numeral;
// Subtract the value of the current Roman numeral from the input number
num -= romanNumeral.value;
}
}
return result;
}
xxxxxxxxxx
/*
// This application helps you convert roman numerals to numbers or vice-versa
*/
// First install the package @ "npm install cr-numeral"
// Then import or require the package in your application
const {
convertNumberToRoman: cnr,
convertRomanToNumber: crn,
} = require("cr-numeral");
// OR
const cnr = require("cr-numeral").convertNumberToRoman;
const crn = require("cr-numeral").convertRomanToNumber;
// Define your variables
const number = 2021;
const numeral = "MMMXXV"; // Case-insensitive
// Use your package/module
const toRoman = cnr(number);
const toNumber = crn(numeral);
// Log or use your result
console.log(toRoman, toNumber);
// Converting a number to Roman Numeral
const { convertNumberToRoman } = require('cr-numeral');
// OR
const convertNumberToRoman = require('cr-numeral').convertNumberToRoman;
convertNumberToRoman(2021));
"MMXXI"
convertNumberToRoman(-2021)); // Can not convert a negative number or zero
"Can not convert Zero or negative numbers!!!"
convertNumberToRoman("na256m"));
"You must provide only valid numbers!!!"
convertNumberToRoman(false));
"Cannot use Boolean values!!!"
convertNumberToRoman(true));
"Cannot use Boolean values!!!"
// Converting Roman Numeral to Number
const { convertRomanToNumber } = require('cr-numeral');
// OR
const convertRomanToNumber = require('cr-numeral').convertRomanToNumber;
convertRomanToNumber("MMXXI"));
"2021"
convertRomanToNumber("na256m"));
"Provide a valid roman character!!!"
"Cause these are invalid roman numerals : [ N,A,2,5,6 ]"
convertRomanToNumber(6355));
"You must provide only valid strings!!!"
convertRomanToNumber(false));
"Cannot use Boolean values!!!"
convertRomanToNumber(true));
"Cannot use Boolean values!!!"
// With love @kouqhar