ParseInt() strange octal behavior [duplicate] - javascript

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

Related

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

Why parseInt() doesn't convert "true" to number, while multiplying does? [duplicate]

This question already has answers here:
parseInt vs unary plus, when to use which?
(6 answers)
Closed 8 years ago.
I started from expression returning true (I choose 1==1) and wrote it in console
cosole.log(1==1);
It logs true. Now I want to convert it to integer (1) and wrap it in parseInt()
console.log(parseInt(1==1));
It logs NaN. Looks like it is trying to convert 1==1 to string before it converts it to number.
Then I'll simply multiply 1==1 by 1.
console.log((1==1)*1);
It logs 1.
Why in first case it converts it converts true to string before converting it to integer (resulting NaN) while I want to convert it to string and in the second case it converts true directly to integer? I'd expect that true*1 will be NaN too.
parseInt, by virtue of being a “parse”r, should take a string and produce an integer, so it converts its argument to a string. *, because it’s multiplication, converts its arguments to numbers.
If you want to convert anything to an (32-bit) integer, | 0 works; it’s a 32-bit bitwise integer operation, and can’t result in NaN, because that’s not a 32-bit integer.
Just to emphasize that parseInt is a wholly inappropriate way of casting anything but a string to an integer: what does this give you?
parseInt(5000000000000000000000000)
(For numbers that big, use Math.round(x), or Math.round(+x) if you like to be explicit.)
parseInt(bool) == NaN
parseInt(bool*1) == parseInt(int) == int
I believe Javascript makes true = 1 and false = 0 when you multiply it.
EDIT: to further this, parseInt(bool*bool) would also work

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,""));

Weird javascript output [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Workarounds for JavaScript parseInt octal bug
I was learning the parseInt() function of javascript and was just trying out, and out of nowhere
parseInt('08') returns 0
moreover,
parseInt('07') returns 7 //which is correct
but again
parseInt('09') returns 0 // really, are you kidding me.?
Either I am crazy or I am missing something?
Its because its doing octal when the string starts with 0.
You should pass the radix of 10 as the second parameter.
You need to specify the radix:
parseInt('08', 10); // base 10 radix
Running your javascript thru JSLint will call this out as well.
From the documentation, parseInt parses the string as octal when the string starts with a 0, if no radix is specified.
No, you're. Only parseInt obeys rules for octal numbers and applies them when the string begins with 0.

Categories

Resources