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?

JavaScript
JavaScript

Advertisement

Answer

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

JavaScript
JavaScript

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