Reputation: 946
The basic question here is how do I know when to use and
what is the critical difference between each of them:
Number.parseInt
method (or just parseInt
),Number.parseFloat
method (or just parseFloat
),Number()
function (or class?),+
operatorfor converting JavaScript values (mostly String
's) to numbers.
Especially since all of them give similar values and can convert String
to its Number
representation:
Number.parseInt("2") // returns 2
Number.parseFloat("2") // returns 2
Number("2") // returns 2
+"2" // returns 2
/* Plus a few more methods... */
eval("2") // returns 2
JSON.parse("2") // returns 2
Upvotes: 4
Views: 3776
Reputation: 933
Number.parseInt()
calls the global function parseInt()
in the background, same with Number.parseFloat()
see: Number.parseInt ECMA and Number.parseFloat ECMA
The calls Number("2")
and "+2"
is identical in the background, they both call ToNumber see: Number and Unary + Operator
When you know what types you are working with, or want a guaranteed type back, use parseFloat
and parseInt
, otherwise it tends to be easier to only use Number()
as it will work within all your calculations, many people choose to use the unary + operator because they find it more pleasing to read/type, but that is only based on preference as it is identical to Number()
.
Also, when you using parseInt()
, you can specify a radix, which is useful in certain applications where you want to work in different number systems, which you cannot do with Number()
If the ECMA standard references does not explain the details for you enough, I will add a summary for you.
Upvotes: 4
Reputation: 2537
Number.parseInt
method (or just parseInt
)
0x
as hexadecimal, if another base was not providedNaN
if the value could not be successfully parsed to an integerNumber.parseFloat
method (or just parseFloat
)
parseInt
, except that it allows for a decimal part to be interpretedNumber()
function (or class?)
parseFloat
, but does not allow trailing text0
for an empty string or a string that only contains whitespacenew
, it returns a primitive numberthe +
operator
Number()
, but in operator form.eval()
"2"
, it will be interpreted as a numeric literal, and return that value since it's the result of the last expression in the programJSON.parse()
"2"
, it will be interpreted as a numeric literal, and return the value that was successfully parsed out of it according to the parsing requirements of JSON.So you decide which is appropriate to use based on their capabilities.
Upvotes: 10