Skip to content
Advertisement

Removing trailing zeros from number if it is an integer [closed]

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.

Advertisement

Answer

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+$/, '');
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement