How to Convert from cm to Meters Using JavaScript with html?

Hello Friends Today, through this tutorial, I will tell you How to Convert centimeters (cm) to meters Using JavaScript With HTML.Here’s how to convert centimeters (cm) to meters using JavaScript within an HTML page:


<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>CM to Meters Converter</title>
<h1>CM to Meters Converter</h1>

<label for="cm_value">Enter value in centimeters (cm):</label>
<input type="number" id="cm_value" name="cm_value" required>
<button type="button" onclick="convert()">Convert</button>

<p id="result"></p>

<script src="script.js"></script>


JavaScript (`script.js`).

function convert() {
// Get the CM value from the input field
const cmValue = document.getElementById("cm_value").value;
// Check if a value was entered
if (!cmValue) {
alert("Please enter a value in centimeters.");
// Validate the input (optional)
if (isNaN(cmValue)) {
alert("Please enter a valid numerical value.");
// Conversion factor (1 cm = 0.01 meters)
const cmToMeters = 0.01;
// Calculate meters
const meters = cmValue * cmToMeters;
// Display the results
const result = `CM value: ${cmValue}<br>Meters: ${meters.toFixed(2)}`; // Format to 2 decimal places
document.getElementById("result").innerHTML = result;


1. HTML.
– This HTML structure is similar to the previous examples, using a button to trigger the conversion with JavaScript.

2. JavaScript (`script.js`).
– The `convert` function is called when the “Convert” button is clicked.
– It retrieves the user input from the `cm_value` input field.
– It checks if a value is entered and displays an alert if not.
– You can optionally add input validation to check for numerical values.
– It defines a conversion factor of 1 cm = 0.01 meters.
– It calculates the meters by multiplying the cm value with the conversion factor.
– It constructs a string containing the original CM value and the converted meters value, formatted to two decimal places using `toFixed(2)`.
– It updates the content of the `result` paragraph element using `innerHTML` to display the final result.