1

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>

5 Answers5

1

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)
Bruno
  • 21
  • 3
0

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

0

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
0

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.

Dan Mullin
  • 4,285
  • 2
  • 18
  • 34
-1

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?

Shameel Uddin
  • 511
  • 2
  • 10