What is the difference between Number.parseFloat()
and parseFloat()
? Is one better than the other?
The parseFloat() function parses a string argument and returns a floating point number.
parseFloat() 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 .
If s does not begin with a number that parseFloat( ) can parse, the function returns the not-a-number value NaN . Test for this return value with the isNaN( ) function. If you want to parse only the integer portion of a number, use parseInt( ) instead of 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.
They are the exact same function. They don't only behave the same. They are the exact same function object.
To expand on that, Number.parseFloat()
was created in ECMAScript 2015, as part of an effort to modularize globals [because global functions with no namespace makes me sad :(]
parseFloat
vs. Number.parseFloat
parseFloat === Number.parseFloat // => true
--
parseFloat
is accessible via the Global scope as of ES2015
parseFloat
From MDN: its purpose is modularization of globals
--
Number.parseFloat
is available via a method on the Number
object (also since ES2015).
In either case, the behavior for both function calls is identical. Both will type coerce the input into a Number if possible (e.g.: parseFloat('67') // => 67
) or return NaN
if the parsed input wasn't able to be coerced.
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