Hello Friends Today, through this tutorial, I will tell you How to Write Program Average calculator using JavaScript with HTML? You can create a simple average calculator using JavaScript and HTML. Here’s a basic example:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Average Calculator</title>
</head>
<body>
<h1>Average Calculator</h1>
<label for="numbers">Enter numbers separated by commas: </label>
<input type="text" id="numbers" placeholder="1 2 3 5 6 6">
<button onclick="calculateAverage()">Calculate Average</button>
<p id="result"></p>
<script>
function calculateAverage() {
let input = document.getElementById('numbers').value;
let numbers = input.split(',').map(num => parseFloat(num.trim()));
let sum = 0;
let average = 0;
// Calculate sum of numbers
for (let number of numbers) {
sum += number;
}
// Calculate average
if (numbers.length > 0) {
average = sum / numbers.length;
}
// Display result
document.getElementById('result').textContent = `Average: ${average.toFixed(2)}`;
}
</script>
</body>
</html>
In this example:
1. Users input numbers separated by commas into the text field.
2. When the “Calculate Average” button is clicked, the `calculateAverage()` function is called.
3. The function retrieves the input string, splits it into an array of numbers using `split(‘,’)`, and converts each element to a floating-point number using `parseFloat()`.
4. It then calculates the sum of all the numbers and divides it by the number of elements to find the average.
5. The result is displayed to the user with two decimal places using `toFixed(2)`.