Home > Enterprise >  Why do I keep getting Nan even though I am using parseFloat function?
Why do I keep getting Nan even though I am using parseFloat function?

Time:08-21

For some reason I keep getting Nan when I am trying to convert Kms to Miles. It seems like the parseFloat function isn't working. Any ideas what can be that I am not seeing?

 document.querySelector('button').onclick = function(){
        let convertt = 0.62;
        let inpput = parseFloat(document.getElementById('inputter'));
            document.getElementById('result').innerHTML = 
            (inpput * convertt)    ' miles';
           
        }
 <h1>Km to miles converter</h1>
    <input type="text" id="inputter">
    <button>Convert</button>
    <div id="result"></div>

CodePudding user response:

When you call document.getElementById, it returns an Element which is a reference to the Element you are handling in the DOM, if there is no Element with the given id, it returns Null. If this element is an input, you can also access the value of it. In this case you use:

document.getElementById('inputter').value

In order to convert it into float, use:

parseFloat(document.getElementById('inputter').value)

CodePudding user response:

Here’s a trick you can do to avoid calling parseFloat altogether.

 document.querySelector('button').onclick = function(){
    let convertt = 0.62;
    let inpput =  document.getElementById('inputter').value;
    document.getElementById('result').innerHTML = (inpput * convertt)    ' miles';
}
<h1>Km to miles converter</h1>
<input type="text" id="inputter">
<button>Convert</button>
<div id="result"></div>

   

CodePudding user response:

I think it's because you're doing document.getElementById('inputter') and not document.getElementById('inputter').value

CodePudding user response:

Instead of parsing the document object itself, you should parse the value contained inside the input field:

parseFloat(document.getElementById("inputter")); // wrong
parseFloat(document.getElementById("inputter").value); // good

CodePudding user response:

Simple JS of what you wrote:

let convertt = 0.62;
let inpput = 1.31;
let result = (inpput * convertt)    ' miles'

Result

'0.8122 miles'

So, the issue is with the data you are getting from the queryselector.

Debug

console.log(inpput)

Check and see if you are getting the data in this variable?

  • Related