0

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);

3 Answers 3

1
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(",");
Sign up to request clarification or add additional context in comments.

4 Comments

how would use a "\n" after the second number? I tried parseFloatt(number1)"\n", but did not work
If you need to enter \n after the second number, just use document.getElementById('inputTextToSave').innerHTML = list.join(",") + "\n";
If what you're after is a newline, you're probably better off using document.getElementById('inputTextToSave').innerHTML = list.join(",") + "<br/>"; to add a line break.
sorry there are more number. the idea is to use "\n" for every other number i.e. 2222, 2222 "\n" 3333, 3333 "\n" 4444, 4444 "\n" ....
0

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);
}

1 Comment

@AlexaAtna can you explain what you are needed?
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.