How do I hide/not print/output when number1 or number2 is NaN or 0 just by modifying below
document.getElementById('inputTextToSave').innerHTML = parseFloat(number1).toFixed(3) + "," + parseFloat(number2).toFixed(3);
var n1 = parseFloat(number1),
n2 = parseFloat(number2),
list = [];
// add values to array if they're not NaN or > 0
if (n1) {
list.push(n1);
}
if (n2) {
list.push(n2);
}
// combine values into a string separated with commas
document.getElementById('inputTextToSave').innerHTML = list.join(",");
\n after the second number, just use document.getElementById('inputTextToSave').innerHTML = list.join(",") + "\n";document.getElementById('inputTextToSave').innerHTML = list.join(",") + "<br/>"; to add a line break.Try this condition number1.trim() is validate NaN And parseFloat(number1) > 0 validate 0
if (number1.trim() && parseFloat(number1) > 0 && number2.trim() && parseFloat(number2) > 0) {
document.getElementById('inputTextToSave').innerHTML = parseFloat(number1).toFixed(3) + "," + parseFloat(number2).toFixed(3);
}
You could collect your values in an array, filter the data with a check for truthyness and map the calculation and fixing. Then join the array for getting a single string. If the string is not empty, assign the value to the HTML element with the given id.
function setResult(array, id) {
var result = array.filter(a => +a).map(a => (2 * a).toFixed(3)).join(', ');
if (result) {
document.getElementById(id).innerHTML = result;
}
}
setResult([0, 0], 'example0');
setResult([10], 'example1');
setResult([10, 0], 'example2');
setResult([10, 20, 30], 'example3');
<div id="example0">-</div>
<div id="example1">-</div>
<div id="example2">-</div>
<div id="example3">-</div>