-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
47 lines (41 loc) · 1.36 KB
/
script.js
File metadata and controls
47 lines (41 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function convert() {
const inputValue = parseFloat(document.getElementById("inputValue").value);
const outputUnit = document.getElementById("outputUnit").value;
const inputUnit = document.getElementById("inputUnit").value;
const resultElement = document.getElementById("resultValue");
if (isNaN(inputValue)) {
resultElement.textContent = "Please enter a number.";
return;
}
let result = 0;
let metersValue = 0;
// Step 1: same unit OR normalize to meters
if (inputUnit === outputUnit) {
result = inputValue;
} else {
// convert input → meters
if (inputUnit === "miles") {
metersValue = inputValue * 1609.34;
} else if (inputUnit === "kilometers") {
metersValue = inputValue * 1000;
} else if (inputUnit === "feet") {
metersValue = inputValue / 3280.84;
} else if (inputUnit === "meters") {
metersValue = inputValue;
}
// convert meters → output
if (outputUnit === "miles") {
result = metersValue / 1609.34;
} else if (outputUnit === "kilometers") {
result = metersValue / 1000;
} else if (outputUnit === "feet") {
result = metersValue * 3280.84;
} else if (outputUnit === "meters") {
result = metersValue;
}
}
const resultString =
inputValue + " " + inputUnit + " = " + result.toFixed(2) + " " + outputUnit;
console.log(resultString);
resultElement.textContent = resultString;
}