+ 4
Convert String to Number: Which method is better and why?
I'm not sure if there are other methods, but I've come across these three. Quick example: parseInt("10.4") == 10 // true parseFloat("10.4") == 10.4 // true Number("10.4") == parseFloat("10.4") // true My question is between parseFloat() and Number(). Since they both do the same thing, which is better to use? I am aware that parseFloat is a built-in function of Number. So if Number() is called, is it just routing everything through parseFloat function? Is it therefore slightly better performance-wise to just call the function directly?
4 Answers
+ 4
They don't "both do the same thing"...
var text_number = "10.4px";
var float = parseFloat(text_number); // 10.4
var num = Number(text_number); // NaN
text_number = "";
float = parseFloat(text_number); // NaN
num = Number(text_number); // 0
However, '+' operator "do the same thing" as Number():
num = + text_number; // 0
text_number = "42";
num = + text_number; // 42
+ 4
That's not issues, that's behaviours ^^
parseFloat() and parseInt() are intended to parse number from string, while Number() is a constructor and is intended to convert any value type to numeric...
0
Interesting! Thanks @visph!
I need to play around with that a bit more. Thanks a lot for your insight.
I see a lot of parseFloat() used most of the time. But it's possible to throw it into an error. I see even in your example that parseFloat("") will result in NaN. Of course more conditions could be given to prevent code from breaking.
Anyway- so far it seems like all methods have their own issues.
0
@visph...
Thanks for your time!
Helps to know the ins-and-outs of methods etc. to know which one to use and why.