!!
always works fine for converting String, undefined
, Object and Number types to Boolean type in JavaScript:
!!0 // false
!!1 // true
!!10 // true
!!"" // true
!!"any" // true
!!undefined // false
!!null // false
!!NaN // false
!!{} // true
It seems using !!
is totally safe. I've seen people using this for converting variables.
But I'm not sure about ++
or --
for converting String types to Number types. In these examples it looks using ++
for converting is safe:
var ten = "10";
ten++ // 10
var nineHalf = "9.5";
nineHalf++ // 9.5
var n = "-10.06";
n++ // -10.06
Is there any case that ++
/--
don't work as parseFloat
?
The parseFloat() function is used to accept the string and convert it into a floating-point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number.
Number: Parses Whitespace and Booleans as NumbersparseFloat will not accept whitespace as an acceptable input, unless it contains a number. In addition to whitespace, Number will also parse booleans as numbers, whereas parseFloat will not.
The parseFloat function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or NaN .
It works with numeric value, no matter whether it's float or int. parseInt or parseFloat are generally used to parse string to number.
Just use a single +
(unary plus operator). It is a common practice just like !!
for booleans.
(+"10.06")
The ++
version makes me afraid of the increment operators doing evil tricks when I'm not looking.
Edit: And of course, the postIncrement operator doesn't even work on string literals.
"10.06"++ //syntax error
The only thing is that it has the side effect of adding one to the original variable. The effect of
var n = "-10.06";
n++
for example, is the same as
var n = "-10.06";
Number(n)++
Basically, any math operator when applied to a string will first convert it to a number using the Number
function.
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