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.
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 .
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.
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.
The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With