5 ms·
I don't agree that using the unary plus operator is a best practice for string->number conversions. Best practices should advocate maintainability and clarity -
by cdsanchez 15y ago
I don't agree that using the unary plus operator is a best practice for string->number conversions. Best practices should advocate maintainability and clarity - in this case parseFloat is the better choice for obvious reasons. Just be aware that parseFloat and unary + aren't exactly equivalent: parseFloat("10x") === 10, +"10x" === NaN.
And no, JavaScript is not a "non-typed language." AFAIK JavaScript is both dynamically and weakly typed. Being in the latter category does mean that it will implicitly convert values to other types in certain scenarios.
- bsimpson 15y agoCasting with Number is also acceptable. I don't understand why he would recommend unary as a replacement for casting. It obfuscates the intent of your code, which is especially concerning since this reads like a guide for beginners.
- VMG 15y agocareful parseFloat("08") === parseFloat("09") === 0 http://stackoverflow.com/questions/850341 http://stackoverflow.com/questions/850341
- cdsanchez 15y agoThat only applies to parseInt because it tries to guess the radix if one isn't supplied. parseFloat assumes base 10 and doesn't accept a radix argument.
- VMG 15y agowhoops, got out of bed too early
- mikemaccana 15y agoOh that's neat. Thankyou.
- deleted 15y ago[deleted]