Skip to content
Advertisement

Why do I keep getting Nan even though I am using parseFloat function? [closed]

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>

Advertisement

Answer

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>

   

EDIT: The comments on this answer have been deleted somehow. Here is context to my answer.

The unary plus operator is used to turn a string into a number. It only works if the entire string can be converted into a number.

parseFloat Will get the first float it recognizes in the string and discard everything after.

Personally, I prefer to use the unary plus in lieu of parseFloat because 99% of the time the string I’m getting back should only ever contain a number.

If my program is expecting a number, using the unary plus operator ensures that nothing but a number will get through.

parseFloat On the other hand, would accept a corrupted string in cases where the string contains invalid characters.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement