One inch equals exactly 2.54 centimeters. Multiply inches by 2.54 to get centimeters, or divide centimeters by 2.54 to get inches.
const centimeters = inches * 2.54;
const inches = centimeters / 2.54;

// Inches to centimeters
centimeters = inches * 2.54;
// Centimeters to inches
inches = centimeters / 2.54;
function inchesToCm(inches) {
return inches * 2.54;
}
function cmToInches(cm) {
return cm / 2.54;
}
The older page combined blur and keyup. For a numeric input that should update while its value changes, the input event covers typing and other value changes more directly.
inchInput.addEventListener("input", () => {
const inches = Number(inchInput.value);
if (Number.isFinite(inches)) {
cmInput.value = (inches * 2.54).toFixed(4);
}
});
Check an empty value separately, then convert and verify that the result is finite. This avoids showing NaN to the user.
See numeric validation for the difference between global isNaN() and Number.isNaN().
The conversion factor should not be shortened. If you want fewer visible decimals, format the output after calculation rather than changing the factor.
Visible labels identify the units without relying only on placeholders. The converter also uses type="number" with step="any" so decimal input is supported.
Continue with feet and meters conversion, getElementById(), and toFixed().
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.