Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Number(...) and parseFloat(...)

What is the difference between parseInt(string) and Number(string) in JavaScript has been asked previously.

But the answers basically focused on the radix and the ability of parseInt to take a string like "123htg" and turn it into 123.

What I am asking here is if there is any big difference between the returns of Number(...) and parseFloat(...) when you pass it an actual number string with no radix at all.

like image 531
Naftali Avatar asked Aug 16 '12 13:08

Naftali


People also ask

What does number parseFloat do?

The Number. parseFloat() method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns NaN .

What does parseFloat mean?

The parseFloat() function is used to accept a string and convert it into a floating-point number. If the input string does not contain a numeral value or If the first character of the string is not a number then it returns NaN i.e, not a number.

What is the difference between parseInt and parseFloat?

parseInt is for converting a non integer number to an int and parseFloat is for converting a non float (with out a decimal) to a float (with a decimal). If your were to get input from a user and it comes in as a string you can use the parse method to convert it to a number that you can perform calculations on.

What is the return type of parseFloat ()?

The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.


1 Answers

The internal workings are not that different, as @James Allardic already answered. There is a difference though. Using parseFloat, a (trimmed) string starting with one or more numeric characters followed by alphanumeric characters can convert to a Number, with Number that will not succeed. As in:

parseFloat('3.23abc'); //=> 3.23 Number('3.23abc'); //=> NaN 

In both conversions, the input string is trimmed, by the way:

parseFloat('  3.23abc '); //=> 3.23 Number('   3.23 '); //=> 3.23 
like image 51
KooiInc Avatar answered Sep 17 '22 20:09

KooiInc