Legacy JS - Roman Numeral Converter

Hello there! What is wrong with this code?

function convertToRoman(num) {
	const numStr = num.toString();
	let u = Number(numStr.charAt(-1));

	let ur = "",
		dr = "",
		cr = "",
		mr = "";
	if (u == 1) {
		ur = "I";
	} else if (u == 2) {
		ur = "II";
	} else if (u == 3) {
		ur = "III";
	} else if (u == 4) {
		ur = "IV";
	} else if (u == 5) {
		ur = "V";
	} else if (u == 6) {
		ur = "VI";
	} else if (u == 7) {
		ur = "VII";
	} else if (u == 8) {
		ur = "VIII";
	} else if (u == 9) {
		ur = "IX";
	} else {
		ur = "";
	}
	if (numStr.length >= 2) {
		let d = Number(numStr.charAt(-2));
		if (d == 1) {
			dr = "X";
		} else if (d == 2) {
			dr = "XX";
		} else if (d == 3) {
			dr = "XXX";
		} else if (d == 4) {
			dr = "XL";
		} else if (d == 5) {
			dr = "L";
		} else if (d == 6) {
			dr = "LX";
		} else if (d == 7) {
			dr = "LXX";
		} else if (d == 8) {
			dr = "LXXX";
		} else if (d == 9) {
			dr = "XC";
		} else {
			dr = "";
		}
	}
	if (numStr.length >= 3) {
		let c = Number(numStr.charAt(-3));
		if (c == 1) {
			cr = "C";
		} else if (c == 2) {
			cr = "CC";
		} else if (c == 3) {
			cr = "CCC";
		} else if (c == 4) {
			cr = "CD";
		} else if (c == 5) {
			cr = "D";
		} else if (c == 6) {
			cr = "DC";
		} else if (c == 7) {
			cr = "DCC";
		} else if (c == 8) {
			cr = "DCCC";
		} else if (c == 9) {
			cr = "CM";
		} else {
			cr = "";
		}
	}
	if (numStr.length >= 4) {
		let m = Number(numStr.charAt(-4));
		if (m == 1) {
			mr = "M";
		} else if (m == 2) {
			mr = "MM";
		} else if (m == 3) {
			mr = "MMM";
		} else {
			mr = "";
		}
	}
	let result = mr + cr + dr + ur;
	return result;
}

What tests are failing? What debugging have you tried so far?

Those variables are a little cryptic.

When I run it it says that it didnt work basically.
The variables are u (units), d (tens), c (hundreds), m (thousands). and their respective r (roman) version

It’s usually best to use words as variable names.

Can you be any more specific?


Have you checked what’s inside your variants u, d, etc? I don’t think it is what you expect

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.