Converting string to number - parseInt() vs Number(); [duplicate] - javascript

This question already has answers here:
What is the difference between parseInt() and Number()?
(11 answers)
Closed 1 year ago.
Why in this situation when i want to convert string to number parseInt() works but Number() not?
parseInt(this.element.style.left) << it works
Number(this.element.style.left) << it doesn't, there is NaN

With parseInt:
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.
In contrast, Number tries to parse the entire argument as a number.
With style.left ending in px, for example, parseInt('12px') works because the px can just be ignored by the parseInt. But Number('12px') doesn't work because all the characters of the '12px' cannot be interpreted as a number.
parseInt skips invalid characters (and stops parsing there), evaluating to what's been parsed so far.
Number fails to parse at all when there are any invalid characters anywhere.

Related

Why parseInt 0.11 is not NaN but 0?

Is this normal?
newItemRowNumber
'0.11'
parseInt(newItemRowNumber)
0
I would expect that it is not parseable.
parseInt parses the string for real numbers 0-9 at the start of the string. When it encounters a non integer character it stops parsing, in this case the .
19aaa becomes 19
0.11 becomes 0
11.111 becomes 11
abc11 becomes NaN
0xDEAD becomes 57005(Because of hexadecimal numbers)
From MDN:
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.
0 is a numerial.
. is not.
So it takes the 0, ignores the ., ignores everything after the ., and you get 0.
This is normal because parseInt will just cut the fraction part from the given number string. And return the int value of the left side number of the dot.
Here is Link parseInt() in JS.
As you are parsing float its better you can use parseFloat()
console.log(parseFloat("0.11"))
>>0.11

ParseInt() strange octal behavior [duplicate]

This question already has answers here:
Why JavaScript treats a number as octal if it has a leading zero
(3 answers)
Closed 4 years ago.
I have to convert some input data to integer.
I found parseInt() function.
Everything is good if the input is string:
console.log(parseInt("123")) //123
Even if the string starts with 0:
console.log(parseInt("0123")) //123
But if a number starts with 0, it will give 83!
console.log(parseInt(0123)) //83 instead of 123
I heard about that's because octal behavior (Javascript parseInt() with leading zeros), so I gave a radix parameter to it:
console.log(parseInt(0123,10)) //83!!!
Still 83!!!
And then, the strangest of all:
I thinked: octal 123 must give 123 in octal!
But it gave NaN:
console.log(parseInt(0123, 8)) //NaN
Why this strange behavior?! And how can I fix it?
Thanks!!!
In this code, you can defined a number (rather than a string) in octal format, then passed it to parseInt. Then parseInt casts that number to a string ("83"), and parses it again.
If you pass a string to parseInt you will get the expected result:
console.log(parseInt('0123'))
You should use a combination of a string and a radix to get the correct value. Here's an example:
parseInt(01234) // returns 668
parseInt('01234', 10) // returns 1234

Leading zeros leading to wrong sorting answer using inbuilt sort method of javascript [duplicate]

This question already has answers here:
Javascript - Leading zero to a number converting the number to some different number. not getting why this happening?
(2 answers)
Closed 5 years ago.
I was sorting a string/array of integers in lexicographical order. A case came when i had to sort a string containing "022" using array.sort. I don't know why it is equating that equal to "18" when being printed.
var l = [022,12];
l.sort();
(2) [12, 18] => output
What is the reason behind this and how to correct it?
I recommend to "use strict"; so that 022 will produce a syntax error instead of octal number:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_octal
This isn't specific to the sort. If you just type 022 into a console, you'll get back 18. This is because 022 is being interpreted as an OctalIntegerLiteral, instead of as a DecimalLiteral. This is not always the case however. Taking a look at the documentation:
Note that decimal literals can start with a zero (0) followed by another decimal digit, but If all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. This won't throw in JavaScript, see bug 957513. See also the page about parseInt().
EDIT: To remove the leading 0s and interpret the 022 as a decimal integer, you can use parseInt and specify the base:
parseInt("022", 10);
> 22

parseInt('1e1') vs parseFloat('1e1')

parseInt(1e1); //10
parseInt('1e1'); //1
parserFloat('1e1') //10
Why parseInt returns 1 in the second case? The three shouldn't return the same result?
1e1 is a number literal that evaluates to 10; parseInt() sees 10 and happily returns that.
'1e1' is a string, and parseInt() does not recognize exponential notation, so it stops at the first letter.
'1e1' as a string is perfectly fine when parsed as a float.
Bonus: parseInt('1e1', 16) returns 481, parsing it as a 3-digit hex number.
When you're trying to parse a string, only the first number in a string is returned. Check function specification at http://www.w3schools.com/jsref/jsref_parseint.asp
Also, you can test it out yourself:
parseInt('2e1') - returns 2
parseInt('3e2') - returns 3
To understand the difference we have to read ecma official documentation for parseInt and parseFloat
... parseInt may interpret only a leading portion of string as an integer value; it ignores any characters that cannot be interpreted as part of the notation of an integer, and no indication is given that any such characters were ignored...
... parseFloat may interpret only a leading portion of string as a Number value; it ignores any characters that cannot be interpreted as part of the notation of an decimal literal, and no indication is given that any such characters were ignored...
parseInt expects ONLY an integer value (1, 10, 28 and etc), but parseFloat expects Number. So, string "1e1" will be automatically converted to Number in parseFloat.
parseInt('1e1'); // 1
parseFloat('1e1'); // 10

In javascript: why does parseInt("08") evaluate to zero, but parseInt(08) evaluate fine? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Workarounds for JavaScript parseInt octal bug
I would think it has something to do with octal parsing, since it only happens on 8 or 9. There was also the thought that this was a Chrome bug, but it replicates in Firefox as well.
Is this intentional behavior? If so, why?
The solution here is simple. NEVER call parseInt() without specifying the desired radix. When you don't pass that second parameter, parseInt() tries to guess what the radix is based on the format of the number. When it guesses, it often gets it wrong.
Specify the radix like this and you will get the desired result:
parseInt("08", 10) == 8;
As to what rules it uses for guessing, you can refer to the MDN doc page for parseInt().
If radix is undefined or 0, JavaScript assumes the following:
If the input string begins with "0x" or "0X", radix is 16
(hexadecimal).
If the input string begins with "0", radix is eight
(octal). This feature is non-standard, and some implementations
deliberately do not support it (instead using the radix 10). For this
reason always specify a radix when using parseInt.
If the input string
begins with any other value, the radix is 10 (decimal). If the first
character cannot be converted to a number, parseInt returns NaN.
So, according to these rules, parseInt() will guess that "08" is octal, but then it encounters a digit that isn't allowed in octal so it returns 0.
When you pass a number to parseInt(), it has nothing to do because the value is already a number so it doesn't try to change it.
"Is this intentional behavior?"
Yes.
"If so, why?"
A leading 0 is the notation used for denoting an octal number as defined in the specification. The symbols 8 and 9 don't exist in octal numbering, so parseInt uses the first valid number it finds, which is 0.
If you do...
parseInt('123#xq$_.f(--_!2*')
...the result will be...
123
...because a valid number was found at the beginning of the string. Anything invalid beyond that is discarded.
You can fix this like that :
parseInt("080".replace(/^[0]+/g,""));

Categories

Resources