How could I fix the NaN error in the code below?
I already tried initializing the variables with 0 but it didn't work.
Ignore the CSS inside the tags, where work needs to be written like this...
This is the code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function NotaFinal() {
var n1 = parseFloat(document.getElementById("n1").value);
var n2 = parseFloat(document.getElementById("n2").value);
var ex = parseFloat(document.getElementById("ex").value);
var MediaFinal = n1 + n2;
if (ex > 0) {
if(MediaFinal > 2.75 && MediaFinal < 5.75) {
MediaFinal = (MediaFinal + (ex*2)) / 3
alert("A nota final é " + MediaFinal.toFixed(1));
}
} else {
alert("A nota final é " + MediaFinal.toFixed(1));
}
}
function Limpar() {
document.getElementById("n1").value = "";
document.getElementById("n2").value = "";
document.getElementById("ex").value = "";
}
</script>
</head>
<body>
<strong><span style="padding-top: 10px; font-family: Arial, Helvetica, sans-serif;">N1</span></strong><input id="n1" type="number"><br><br>
<strong><span style="padding-top: 10px; font-family: Arial, Helvetica, sans-serif;">N2</span></strong><input id="n2" type="number"><br><br>
<strong><span style="padding-top: 10px; font-family: Arial, Helvetica, sans-serif;">EX</span></strong><input id="ex" type="number"><br><br>
<button onclick="NotaFinal()" style="background-color: #0C5BA1; color: #FFFFFF; border: none; padding: 2px; width:70px; margin-left: 23px;">Calcular</button>
<button onclick="Limpar()" style="background-color: #0C5BA1; color: #FFFFFF; border: none; padding: 2px; width: 70px; margin-left: 20px;">Limpar</button>
</body>
</html>
based on @wck's error reproduction:
As you can see (1), (2), (3) I have added .replace(',', '.') to replace the first
,found with a dot
.according to the standard about type of programming language if there are two signs
,` then it is no longer a number and will return NaN
function NotaFinal() {
var n1 = parseFloat(document.getElementById("n1").value.replace(',', '.')); // (1)
var n2 = parseFloat(document.getElementById("n2").value.replace(',', '.')); // (2)
var ex = parseFloat(document.getElementById("ex").value.replace(',', '.')); // (3)
var MediaFinal = n1 + n2;
if (ex > 0) {
if (MediaFinal > 2.75 && MediaFinal < 5.75) {
MediaFinal = (MediaFinal + (ex*2)) / 3
alert("A nota final é " + MediaFinal.toFixed(1));
}
} else {
alert("A nota final é " + MediaFinal.toFixed(1));
}
}