0

I'm trying to convert a string to a float. I know that parseFloat() can do that, but I've also found the syntax below, but without much reference.

What is the correct syntax, because they all seem to work. And where can I learn more about it? I don't know how to Google it, because I don't know what it's named.

// syntax 1
alert((+"123"));    // 123
alert((+"x123"));   // NaN
alert((+"123x"));   // NaN
alert((+"123   ")); // 123
alert((+"   123")); // 123
alert((+"12 3"));   // NaN

// syntax 2
alert(+"123");      // 123
alert(+"x123");     // NaN
alert(+"123x");     // NaN
alert(+"123   ");   // 123
alert(+"   123");   // 123
alert(+"12 3");     // NaN

// syntax 3
alert(+("123"));    // 123
alert(+("x123"));   // NaN
alert(+("123x"));   // NaN
alert(+("123   ")); // 123
alert(+("   123")); // 123
alert(+("12 3"));   // NaN
wubbewubbewubbe
  • 711
  • 1
  • 9
  • 20
  • 1
    The extra `( )` don't do anything special here, because they are just grouping a single computed value (syntax 1) or literal (syntax 3), and the meaning is no different if you remove the `( )`. If you were to do something like `alert(+("123" + "456"));`, then the extra `( )` would be doing something meaningful, and the computation would change with their removal (although the result would end up being the same, but the way in which you get there would not be). – ajp15243 Apr 24 '13 at 14:33
  • 1
    Also, [this question about JavaScript unary operators](http://stackoverflow.com/questions/12120802/explain-var-and-var-unary-operator-in-javascript) may help answer your question. – ajp15243 Apr 24 '13 at 14:36

2 Answers2

3

They're all syntactically correct...but examples 1 and 3 have redundant brackets.

Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
2

This is called implicit conversion. Since you used a mathematical operator (+), it tries to convert the string to a numeric value which is needed for mathematical operations. What you are asking here is give me the positive value of the following string.

Dominic Goulet
  • 7,983
  • 7
  • 28
  • 56