0

I want to print the err variable to the payment Id if downtimeTotal is NaN or null or 0 (so essentially if the user doesn't put any inputs) but the calculator still prints NaN.

    <div class="totalwrapper">Credit Total:$<span id="payment" class="output"></span></div>
    </div>
    <button id="btn">Calculate</button>
    

    <script> 
    let btn = document.getElementById('btn')
    btn.addEventListener('click', function(){
        let err = "you didn't put any numbers in!"
        let rmr = document.getElementById('RMR').value;
        let cam = document.getElementById('bcam').value;
        let sens = document.getElementById('sensors').value;
        let dayMonth = document.getElementById('days').value;
        let bSensors = document.getElementById('badSensors').value;
        let down = document.getElementById('daysDown').value;
        let rmrCam = cam * 5 / dayMonth * down;
        let getDowntime = rmr / sens / dayMonth * bSensors * down + rmrCam;
        if (sens == 0 || NaN || null ) {
            getDowntime = rmr / dayMonth * bSensors * down + rmrCam;
        }
        let downtimeTotal = getDowntime.toFixed(2)
        if (downtimeTotal == NaN || null || 0.00){
            document.getElementById("payment").innerHTML = err;
        }else {
            document.getElementById("payment").innerHTML = downtimeTotal;
        }
    
    
    })
    </script>
  • 1
    `NaN == NaN` is always false, iirc, disregarding your improper multiple or statement attempt – Taplar Dec 03 '20 at 17:52
  • See [How do you check that a number is NaN in JavaScript?](https://stackoverflow.com/questions/2652319/how-do-you-check-that-a-number-is-nan-in-javascript) and [How to force JS to do math instead of putting two strings together](https://stackoverflow.com/questions/4841373/how-to-force-js-to-do-math-instead-of-putting-two-strings-together) – Ivar Dec 03 '20 at 17:55

1 Answers1

0

It's a precedence problem in that you're comparing against NaN, then if that's not truty (which it never is), using null and if that's not truthy (which is never is) using zero. See the following as an example:

> a = 0
0
> (a == NaN || 0)
0
> (a == (NaN || 0))
true
> 

But it's also a logic problem in that you're trying to do three comparisons but only one of the ops is a comparison - so it still won't achieve what you want.

To get it working you'd to need to change:

if (sens == 0 || NaN || null ) {

to:

if (sens == 0 || sens == NaN || sens == null) {

But that still won't work because, as stated above NaN == NaN is always false so what you need is something more like:

if (sens === 0 || sens === null || isNan(sens)) {
Richard Wheeldon
  • 973
  • 10
  • 25