-2

I'm reading from a text file some numbers. Sometimes there's a number 0 and the line below outputs 0, but I don't want to output if the number is "0". Is there a way to change the line below to NOT output/print when the number is "0"? Thanks

document.getElementById('inputText').innerHTML= "(" + parseFloat(output1*2).toFixed(3) + "," +  parseFloat(output2*2).toFixed(3) + ")";
Alexa Atna
  • 89
  • 1
  • 8

4 Answers4

1

You can make a function that checks each value and generates a result based on that, like this:

var getResult = function (num1, num2) {
  var result1 = num1 ? (parseFloat(num1) * 2).toFixed(3) : "";
  result1 = isNaN(result1) ? "" : result1;
  var result2 = num2 ? (parseFloat(num2) * 2).toFixed(3) : "";
  result2 = isNaN(result2) ? "" : result2;
  var comma = result1 && result2 ? ", " : "";
  return `(${result1}${comma}${result2})`;
};

document.getElementById('result').innerHTML += `5, 0 = ${getResult("5")}<br/>`;
document.getElementById('result').innerHTML += `0, 4 = ${getResult("0", "4")}<br/>`;
document.getElementById('result').innerHTML += `3, 2 = ${getResult("3", "2")}<br/>`;
document.getElementById('result').innerHTML += `3, 2 = ${getResult("three", "15.5")}<br/>`;
<div id="result"></div>

Edit: Removed possible NaN-results.

Marco de Zeeuw
  • 496
  • 3
  • 10
  • @AlexaAtna If something that can't be resolved to a float by `parseFloat`, this will return `NaN`, so depending on how you use it you might want to add validation for this. For an `isNumeric` function in javascript, check out https://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers – Marco de Zeeuw Aug 20 '17 at 11:31
  • @AlexaAtna Excluding NaN-results is now included in the snippet. – Marco de Zeeuw Aug 20 '17 at 11:44
0

You can replace 0 with nothing using the or operator:

parseFloat(output1*2) || ""

or using a ternary:

output1? parseFloat(output1*2).toFixed(3) : ""
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

Use if statement to check your number:

Html:

<p id="inputText">
   0
</p>

Js:

var output  = document.getElementById('inputText').innerHTML;
output = parseFloat(output);
if(output  != '0'){
inputText.innerHTML= "(" + (output *2)
.toFixed(3) + "," +  (output*2).toFixed(3) + ")";
}

https://jsfiddle.net/b5st3h2m/2/

Alex
  • 113
  • 10
0

document.getElementById('inputText').innerHTML= "(" + ((parseFloat(output1*2).toFixed(3) + ",") ? parseFloat(1*2).toFixed(3):"") + ((parseFloat(output2*2).toFixed(3)) ? parseFloat(1*2).toFixed(3):"") + ")";

rajkris
  • 1,775
  • 1
  • 9
  • 16