Differencebetween Unary Plus/Number(X) and Parsefloat(X)

What is the difference between Unary Plus/Number(x) and parseFloat(x)?

The difference between parseFloat and Number

parseFloat/parseInt is for parsing a string, while Number/+ is for coercing a value to a number. They behave differently. But first let's look at where they behave the same:

parseFloat('3'); // => 3
Number('3'); // => 3
parseFloat('1.501'); // => 1.501
Number('1.501'); // => 1.501
parseFloat('1e10'); // => 10000000000
Number('1e10'); // => 10000000000

So as long as you have standard numeric input, there's no difference. However, if your input starts with a number and then contains other characters, parseFloat truncates the number out of the string, while Number gives NaN (not a number):

parseFloat('1x'); // => 1
Number('1x'); // => NaN

In addition, Number understands hexadecimal input while parseFloat does not:

parseFloat('0x10'); // => 0
Number('0x10'); // => 16

But Number acts weird with empty strings or strings containing only white space:

parseFloat(''); // => NaN
Number(''); // => 0
parseFloat(' \r\n\t'); // => NaN
Number(' \r\n\t'); // => 0

On the whole, I find Number to be more reasonable, so I almost always use Number personally (and you'll find that a lot of the internal JavaScript functions use Number as well). If someone types '1x' I prefer to show an error rather than treat it as if they had typed '1'. The only time I really make an exception is when I am converting a style to a number, in which case parseFloat is helpful because styles come in a form like '3px', in which case I want to drop the 'px' part and just get the 3, so I find parseFloat helpful here. But really which one you choose is up to you and which forms of input you want to accept.

Note that using the unary + operator is exactly the same as using Number as a function:

Number('0x10'); // => 16
+'0x10'; // => 16
Number('10x'); // => NaN
+'10x'; // => NaN
Number('40'); // => 40
+'40'; // => 40

So I usually just use + for short. As long as you know what it does, I find it easy to read.

parseInt vs unary plus, when to use which?

Well, here are a few differences I know of:

  • An empty string "" evaluates to a 0, while parseInt evaluates it to NaN. IMO, a blank string should be a NaN.

      +'' === 0;              //true
    isNaN(parseInt('',10)); //true
  • The unary + acts more like parseFloat since it also accepts decimals.

    parseInt on the other hand stops parsing when it sees a non-numerical character, like the period that is intended to be a decimal point ..

      +'2.3' === 2.3;           //true
    parseInt('2.3',10) === 2; //true
  • parseInt and parseFloat parses and builds the string left to right. If they see an invalid character, it returns what has been parsed (if any) as a number, and NaN if none was parsed as a number.

    The unary + on the other hand will return NaN if the entire string is non-convertible to a number.

      parseInt('2a',10) === 2; //true
    parseFloat('2a') === 2; //true
    isNaN(+'2a'); //true
  • As seen in the comment of @Alex K., parseInt and parseFloat will parse by character. This means hex and exponent notations will fail since the x and e are treated as non-numerical components (at least on base10).

    The unary + will convert them properly though.

      parseInt('2e3',10) === 2;  //true. This is supposed to be 2000
    +'2e3' === 2000; //true. This one's correct.

    parseInt("0xf", 10) === 0; //true. This is supposed to be 15
    +'0xf' === 15; //true. This one's correct.

+ operator vs parseFloat

Citing MDN docs for parseFloat:

parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed.


Using [unary plus operator][2] you may be sure that `parseFloat` operates on `Number`, which is only useful if you want to be more strict about results but still want to use a `parseFloat`
parseFloat('0.32abcd') // -> 0.32
parseFloat(+'0.32abcd') // -> NaN

**Update:**

After a bit of digging in docs and running some tests, seems there is no reason to use parseFloat other than parsing strings that may contain numbers with non numeric trails to number, eq:

parseFloat('31.5 miles') // -> 31.5
parseFloat('12.75em') // -> 12.75

For any other cases where your string contains number + is a fastest and prefered way (citing MDN docs for unary plus operator):

unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number.

See parseFloat versus unary test case for how faster it is.

Previous link broken so here is the new test that shows how unary is faster.

What is the difference between parseInt() and Number()?

Well, they are semantically different, the Number constructor called as a function performs type conversion and parseInt performs parsing, e.g.:

// parsing:
parseInt("20px"); // 20
parseInt("10100", 2); // 20
parseInt("2e1"); // 2

// type conversion
Number("20px"); // NaN
Number("2e1"); // 20, exponential notation

Also parseInt will ignore trailing characters that don't correspond with any digit of the currently used base.

The Number constructor doesn't detect implicit octals, but can detect the explicit octal notation:

Number("010");         // 10
Number("0o10") // 8, explicit octal

parseInt("010"); // 8, implicit octal
parseInt("010", 10); // 10, decimal radix used

And it can handle numbers in hexadecimal notation, just like parseInt:

Number("0xF");   // 15
parseInt("0xF"); //15

In addition, a widely used construct to perform Numeric type conversion, is the Unary + Operator (p. 72), it is equivalent to using the Number constructor as a function:

+"2e1";   // 20
+"0xF"; // 15
+"010"; // 10

Behavior of JS unary plus operator applied on a string representing a negative hex

It may - or may not be seen as a flaw, depending on how one's attached to specifications. )

I've found an interesting discussion regarding this behavior. Looks like Firefox was for once in the 'better-than-spec' camp, but then fixed it according to spec.

Why does the addition (plus) operator produce a string when the left operand is a number and the right one is a string?

Because the spec says so. See The Addition operator (+):


  1. If Type(lprim) is String or Type(rprim) is String, then

    1. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
  2. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).

So it only matters whether some operand is a string, but not which one.

Extract number form a hexadecimal dataFrame parseInt()ParseFloat()

I think this is what you need. String received by function yourStringToFloat is your data variable received by main function in your example. Of course you can fix precision according to your needs.

function flipHexString(hexValue, hexDigits) {
var h = hexValue.substr(0, 2);
for (var i = 0; i < hexDigits; ++i) {
h += hexValue.substr(2 + (hexDigits - 1 - i) * 2, 2);
}
return h;
}

function hexToFloat(hex) {
var s = hex >> 31 ? -1 : 1;
var e = (hex >> 23) & 0xFF;
return s * (hex & 0x7fffff | 0x800000) * 1.0 / Math.pow(2, 23) * Math.pow(2, (e - 127))
}

function yourStringToFloat(str){

return hexToFloat(flipHexString("0x"+str.substr(10), 8))

}

console.log(yourStringToFloat('450934644ad7a38441'));


Related Topics



Leave a reply



Submit