Tell us what’s happening:
Issue with values under 1000 on roman numeral converter. Code works for numbers over 1000 correctly.
Also works when the variable for the input value is passed into the template literal without the convertToRoman function.
And works when a number is passed into the convertToRoman function directly instead of the variable for input.value
When put together it returns M (roman numeral for 1000) for any number under 1000
Your code so far
<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Numeral Converter</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<h1>Roman Numeral Converter</h1>
<main>
<input id="number"></input>
<button id="convert-btn">Convert</button>
<div id="output"></div>
</main>
<script src="script.js"></script>
</body>
</html>
/* file: styles.css */
/* file: script.js */
const numInput = document.getElementById('number');
const convertBtn = document.getElementById('convert-btn');
const resultDiv = document.getElementById('output');
function convertToRoman(num) {
const numerals = {
1: 'I',
4: 'IV',
5: 'V',
9: 'IX',
10: 'X',
40: 'XL',
50: 'L',
90: 'XC',
100: 'C',
400: 'CD',
500: 'D',
900: 'CM',
1000: 'M'
}
let result = '';
const numKeys = Object.keys(numerals).reverse();
numKeys.forEach(key => {
while (key <= num) {
result += numerals[key];
num -= key;
}
});
return result;
}
function runConversion() {
const normNum = numInput.value;
if (normNum === '') {
resultDiv.innerHTML = 'Please enter a valid number.';
} else if (normNum < 0) {
resultDiv.innerHTML = 'Please enter a number greater than or equal to 1.';
} else if (normNum > 3999) {
resultDiv.innerHTML = 'Please enter a number less than or equal to 3999.';
} else {
// resultDiv.innerHTML = `${convertToRoman(normNum)}`
resultDiv.innerText = `${convertToRoman(normNum)}`
}
}
convertBtn.addEventListener('click', runConversion);
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36
Challenge Information:
Build a Roman Numeral Converter Project - Build a Roman Numeral Converter