0

I am creating a script that finds the average temperature after the "mixing" of two volumes. The variables are called: coldWeight warmWeight coldTemp warmTemp. The formula sounds:

However, my code here which works as long as I don't use decimal numbers two places.

    function averagetemp() {
        let coldWeight = document.getElementById('coldWeight').value;
        let warmWeight = document.getElementById('warmWeight').value;
        let coldTemp = document.getElementById('coldTemp').value;
        let warmTemp = document.getElementById('warmTemp').value;     
        
        var html = (warmWeight *warmTemp +coldWeight *coldTemp )/(coldWeight +warmWeight );   
        var html = html.toFixed(2);
        
        document.getElementById('result').innerHTML = html;
    }

It displays NaN every time I have a decimal number in coldWeight and warmWeight. None of the others. To compensate for the str to float, I use step=0.01 in all of the input divs.

Mark
  • 23
  • 4
  • 1
    The `.value` property of a DOM node always returns a string. Parse them first into actual numbers -> `parseFloat()` – Andreas Sep 10 '20 at 09:48
  • 1
    The problem is specifically with `coldWeight +warmWeight`: that will *concatenate* two strings instead of adding their values. Change to `+coldWeight + +warmWeight` and you're done. – trincot Sep 10 '20 at 09:49

0 Answers0