Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I always use ++ or -- as a shorthand for parseFloat?

Tags:

javascript

!! 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?

like image 844
Mohsen Avatar asked Oct 11 '11 01:10

Mohsen


People also ask

How do you use 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.

What is the difference between number and parseFloat?

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.

What does the function parseFloat () do?

The parseFloat function converts its first argument to a string, parses that string as a decimal number literal, then returns a number or NaN .

Does parseFloat work for integers?

It works with numeric value, no matter whether it's float or int. parseInt or parseFloat are generally used to parse string to number.


2 Answers

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
like image 63
hugomg Avatar answered Sep 28 '22 01:09

hugomg


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.

like image 28
airportyh Avatar answered Sep 28 '22 00:09

airportyh