So I am learning javascript, and I have not been working with it for very long, and I have the following code:
function doslope() {
var b, m;
x1 = parseFloat(document.getElementById("x1").value);
y1 = parseFloat(document.getElementById("y1").value);
x2 = parseFloat(document.getElementById("x2").value);
y2 = parseFloat(document.getElementById("y2").value);
m = (y2 - y1) / (x2 - x1);
b = y1 - m * x1;
m = m.toFixed(2);
b = b.toFixed(2);
if (Number.isInteger(m)) {
m = parseInt(m.toString());
}
if (Number.isInteger(b)) {
b = parseInt(b.toString());
}
document.getElementById("result").innerHTML = "y=" + m + "x+" + b;
}
<label>x1<input id="x1" /></label><br>
<label>y1<input id="y1" /></label><br>
<label>x2<input id="x2" /></label><br>
<label>y2<input id="y2" /></label><br>
<button onclick="doslope()">Do slope</button><br>
<br>
<output id="result"></output>
When I run this with the numbers x1=5, y1=5, x2=6, and y2=3 I get the result y=-2.00x+15.00.
I am wondering what error I am making here that it is not removing the .00 at the end of the number.
The problem is that the if statements you have, are returning you false, so you are not making the parseInt, if you take them out, it works correctly:
function doslope() {
var b, m;
x1 = parseFloat(5);
y1 = parseFloat(5);
x2 = parseFloat(6);
y2 = parseFloat(3);
m = (y2 - y1) / (x2 - x1);
b = y1 - m * x1;
m = m.toFixed(2);
b = b.toFixed(2);
m = parseInt(m.toString());
b = parseInt(b.toString());
document.getElementById("result").innerHTML = "y=" + m + "x+" + b;
}
Why are you using that if statement?
If you want that the user can only put numbers, you can try with something like this: type="number" just allows to put numbers, and step="0.01" allows you to put decimal numbers
<label>x1<input id="x1" type="number" step="0.01" /></label><br>
<label>y1<input id="y1" type="number" step="0.01" /></label><br>
<label>x2<input id="x2" type="number" step="0.01" /></label><br>
<label>y2<input id="y2" type="number" step="0.01" /></label><br>
Number.isInteger() checks the type of the value and since your m and b variables are string it will always return false.
What you could do is temporarily convert them into float:
if (Number.isInteger(parseFloat(m))) {
m = parseInt(m.toString());
}
Alternatively (and in your case I think would be a better option) is to simply remove .00 from the string itself:
m = m.toFixed(2).replace(/\.?0+$/, '');
b = b.toFixed(2).replace(/\.?0+$/, '');