+ operator vs parseFloat - javascript

Example 1 of the knockout extenders page describes a way of rounding user input and making sure it is only numeric.
It works great, but looking through the source they do a peculiar thing that i don't understand, that is on line 8 they do this:
parseFloat(+newValue)
newValue is a string.
When i initially asked this question I didn't know what + did - some further poking and a link to a different MDN page from one of the initial answers I got indicate it is a unary operator equivalent to number(str) and that there are some differences between +str and parseFloat(str) (treatment of strings ending in alpha characters and interpretation of hex seem to be the headlines).
I still don't understand why the + in this case needed to be wrapped in the parseFloat although I am starting to think it might be a typo...

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.

Related

What is the critical difference between 'Number.parseInt()', 'Number.parseFloat()', 'Number()' or '+'?

The basic question here is how do I know when to use and
what is the critical difference between each of them:
The Number.parseInt method (or just parseInt),
Number.parseFloat method (or just parseFloat),
Number() function (or class?),
and the + operator
for converting JavaScript values (mostly String's) to numbers.
Especially since all of them give similar values and can convert String to its Number representation:
Number.parseInt("2") // returns 2
Number.parseFloat("2") // returns 2
Number("2") // returns 2
+"2" // returns 2
/* Plus a few more methods... */
eval("2") // returns 2
JSON.parse("2") // returns 2
Number.parseInt method (or just parseInt)
Ignores leading and trailing whitespace
Parses a leading number to an integer (not a floating point number)
Ignores invalid trailing data
Lets you set the base to use when interpreting the number
Will interpret text starting with 0x as hexadecimal, if another base was not provided
Returns NaN if the value could not be successfully parsed to an integer
Number.parseFloat method (or just parseFloat)
Similar to parseInt, except that it allows for a decimal part to be interpreted
Only parses to base-10
Number() function (or class?)
Similar to parseFloat, but does not allow trailing text
Will return 0 for an empty string or a string that only contains whitespace
It's not a class; when called without new, it returns a primitive number
the + operator
Basically the same as Number(), but in operator form.
eval()
Interprets and executes the given input as a JavaScript program.
Given the string "2", it will be interpreted as a numeric literal, and return that value since it's the result of the last expression in the program
Throws an error if the input was not a valid program.
JSON.parse()
Parses the textual data as JSON-serialized data.
If the data is valid, it creates the JavaScript objects/primitives that are represented by the data, and returns them.
If the data is invalid, it throws an error.
Given the string "2", it will be interpreted as a numeric literal, and return the value that was successfully parsed out of it according to the parsing requirements of JSON.
So you decide which is appropriate to use based on their capabilities.
Number.parseInt() calls the global function parseInt() in the background, same with Number.parseFloat() see: Number.parseInt ECMA and Number.parseFloat ECMA
The calls Number("2") and "+2" is identical in the background, they both call ToNumber see: Number and Unary + Operator
When you know what types you are working with, or want a guaranteed type back, use parseFloat and parseInt, otherwise it tends to be easier to only use Number() as it will work within all your calculations, many people choose to use the unary + operator because they find it more pleasing to read/type, but that is only based on preference as it is identical to Number().
Also, when you using parseInt(), you can specify a radix, which is useful in certain applications where you want to work in different number systems, which you cannot do with Number()
If the ECMA standard references does not explain the details for you enough, I will add a summary for you.

Why is it recommended to provide optional radix parameter to parseInt()?

I've always used the parseInt() function in Javascript without passing the radix parameter. As per the MDN documentation here, it's stated that not providing this parameter may result in unpredictable behaviour.
Always specify this parameter to eliminate reader confusion and to
guarantee predictable behavior.
Could somebody clarify what does this unpredictable behavior mean with some code examples?
In older versions of the language, parseInt() would cause the function to obey the normal JavaScript numeric constant syntax rules, including the recognition of a leading zero to denote octal constants, and a leading 0x to denote hex constants. Thus, if your code didn't explicitly insist on base 10, stray (possibly user-supplied) numbers with leading zeros would be interpreted as base-8 values, and leading 0x as hex.
The base-8 behavior is gone since ES5.1 (I think; might have been earlier), but the base 16 behavior is still there. (Probably a leading 0x is a little more rare as an accidental prefix than a simple leading 0.)
My experience looking at code here on Stack Overflow is that parseInt() is overused anyway. It's usually cleaner to convert strings (often, strings taken from DOM element .value properties) to numbers with the unary + operator:
var count = +document.getElementById("count").value;
That won't necessarily give you an integer, of course. However, what it will do is notice that the input string has trailing non-numeric garbage. The parseInt() function will simply stop parsing a string like "123abc" and give you 123 as the numeric value. The leading + will however give you a NaN.
If you need integers, you can always use Math.floor() or Math.round().
edit — a comment notes that ES2015 requires a leading 0o or 0O in "strict" mode for octal literals, but that doesn't apply to parseInt() which (in ES2015) only overrides the default radix for hex strings.
For some reason best known to themselves, the folk specifying the behaviour of this function set the radix to be a defaultable parameter but then decided to leave the default value up to the implementation! (Perhaps it would have been sensible to insist on a value of 10 but maybe that would have upset folk progamming in the 1970s who still consider octal literals to be useful.)
So for robust progamming, you need to supply the radix parameter yourself.
Without supplying the radix, parseInt tries to determine what the right radix is by the value you pass in, for example if the value starts 0x then it determines you must be passing in hex values. Same applies with 0 (octal).
This becomes problematic when your input is zero-padded but no radix is supplied. Where the result will (possibly) not be as expected
console.log(parseInt(015))

using division operator (/) on strings in javascript

I realized that in javascript all 101/100, "101"/100, 101/"100" and "101"/"100" result in 1.01 (checked on Chrome, FF and IE11). But I cannot find a piece of documentation regarding this behaviour.
Therefore my question is if it is (cross-browser) safe to use this feature, and if it is a good practice to do so (or rather to use parseInt before division if the variable can be a string)?
When you use / on strings, the strings are implicitly converted to numbers and then division operation is performed.
This may work in all browsers, but it's always good practice to convert to number explicitly using parseInt or parseFloat or other method.
parseInt("101", 10) / 100
Or
parseFloat("101") / 100
ECMAScript Specifications for Division Operator
Therefore my question is if it is (cross-browser) safe to use this feature...
It depends on your definition of "safe." With the division operator, yes, it's specified behavior: Each operand is converted (implicitly coerced) to a number, and then numeric division is done.
But beware of generalizing this too far. You'll be okay with /, *, and - but it will bite you on +, because if either operand to + is a string, + does string concatenation, not addition.
Another way that it may or may not be "safe" depending on your point of view is the implicit coercion: It uses the browser's JavaScript engine's rules for converting strings to numbers. Some older browsers went beyond the specification (which they were allowed to in the past) and treated numbers starting with a 0 as octal (base 8) rather than decimal. Naturally, end users who type in, say, "0123" as a number probably mean the number 123, not the number 83 (123 in octal = 83 decimal). JavaScript engines are no longer allowed to do that, but some older ones do.
In general, it's probably best to explicitly coerce or convert those operands. Your choices for doing so:
The unary + operator: value = +value will coerce the string to a number using the JavaScript engine's standard rules for that. Any non-digits in the string (other than the e for scientific notation) make the result NaN. Also, +"" is 0, which may not be intuitive.
The Number function: value = Number(value). Does the same thing as +.
The parseInt function, usually with a radix (number base): value = parseInt(value, 10). The downside here is that parseInt converts any number it finds at the beginning of the string but ignores non-digits later in the string, so parseInt("100asdf", 10) is 100, not NaN. As the name implies, parseInt parses only a whole number.
The parseFloat function: value = parseFloat(value). Allows fractional values, and always works in decimal (never octal or hex). Does the same thing parseInt does with garbage at the end of the string, parseFloat("123.34alksdjf") is 123.34.
So, pick your tool to suit your use case. :-)
Type coercion is at play here. Quoting #Barmar's answer from What exactly is Type Coercion in Javascript?
Type coercion means that when the operands of an operator are of different types, one of them will be converted to an "equivalent" value of the other operand's type.
The reason for your observation is valid for other operations too -
1 + "2" will give you "12"
1 - "2" will give you -1
(because "-" operation on strings is not defined like division")
In the case "101/100" the operation "/" will decide the coercion, since there is no operation defined on strings with that operator "/", but is there for "numbers".
Using it is safe (at least in modern browsers) as long as you are clear how type coercion will play out in your operation.

Why parsing a very large number to integer return 1

parseInt(123123123123123123123123); //return 1
parseInt(123123123123123123123123123); //return 1
parseInt(123123123123123123123123123123);//return 1
Test in chrome!
A little creative reading of the documentation for parseInt() provides an answer for this. Here's what's happening:
parseInt expects its first argument to be a string. If it isn't, it converts it to a string. This is actually hilarious, because it appears to do that by...wrapping it in quotes and passing it through .toString(), which is more or less the converse of parseInt() in this case. In your example, parseInt(123123123123123123123123); becomes parseInt("1.2312312312312312e+29").
THEN it takes the converted-to-string value and passes it through parseInt(). As the documentation tells us, if it encounters a non-numeric character, it aborts and goes with what it has so far...and it truncates to an integer. So it's taking "1.2312312312312312e+29", reaching the +, aborting, parsing "1.2312312312312312" instead, and coming up with 1.
Unintended consequences!
You'll only see this problem with ints large enough that when converted to strings, they render in exponential notation. The underlying problem is that even though you'd think parseInt() and Number.toString() would mirror each other...they don't, quite, because int values passed through toString() can generate strings that parseInt() doesn't understand.
First, always specify the radix (second parameter) to avoid guessing.
Second, parseInt expects a string, so add quotes around your number.
parseInt("123123123123123123123123123123", 10)
1.2312312312312312e+29
Mozilla developer reference has good documentation of this function and examples. Regarding the radix, they say:
Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.

JSON.parse parses / converts big numbers incorrectly

My problem is really simple but I'm not sure if there's a "native" solution using JSON.parse.
I receive this string from an API :
{ "key" : -922271061845347495 }
When I'm using JSON.parse on this string, it turns into this object:
{ "key" : -922271061845347500 }
As you can see, the parsing stops when the number is too long (you can check this behavior here). It has only 15 exact digits, the last one is rounded and those after are set to 0. Is there a "native" solution to keep the exact value ? (it's an ID so I can't round it)
I know I can use regex to solve this problem but I'd prefer to use a "native" method if it exists.
Your assumption that the parsing stops after certain digits is incorrect.
It says here:
In JavaScript all numbers are floating-point numbers. JavaScript uses
the standard 8 byte IEEE floating-point numeric format, which means
the range is from:
±1.7976931348623157 x 10308 - very large, and ±5 x 10-324 - very small.
As JavaScript uses floating-point numbers the accuracy is only assured
for integers between: -9007199254740992 (-253) and 9007199254740992
(253)
You number lies outside the "accurate" range hence it is converted to the nearest representation of the JavaScript number. Any attempt to evaluate this number (using JSON.parse, eval, parseInt) will cause data loss. I therefore recommend that you pass the key as a string. If you do not control the API, file a feature request.
The number is too big to be parsed correctly.
One solution is:
Preprocessing your string from API to convert it into string before parsing.
Preform normal parsing
Optionally, you could convert it back into number for your own purpose.
Here is the RegExp to convert all numbers in your string (proceeded with :) into strings:
// convert all number fields into strings to maintain precision
// : 922271061845347495, => : "922271061845347495",
stringFromApi = stringFromApi.replace(/:\s*(-?\d+),/g, ': "$1",');
Regex explanation:
\s* any number of spaces
-? one or zero '-' symbols (negative number support)
\d+ one or more digits
(...) will be put in the $1 variable

Categories