Weird javascript output [duplicate] - javascript

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.

Related

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

javascript parseInt error conversion [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to parseInt a string with leading 0
I'm using Google Chrome ver. 21.0.1180.89
I execute:
var a="07:30";
console.log(a.substring(0,2)+" --> "+parseInt(a.substring(0,2)));
the output is right: "07 --> 7" OK
I execute:
var a="08:30";
console.log(a.substring(0,2)+" --> "+parseInt(a.substring(0,2)));
the output is right: "08 --> 0" WRONG
why?
String begins with "0" taken as octal. You have to set radix 10 in parseInt()
Try this,
var a="08:30";
console.log(a.substring(0,2)+" --> "+parseInt(a.substring(0,2), 10));​
add a radix(base): parseInt(a.substring(0,2), 10). What's happening is your js engine is trying to guess what base the string is, and it's guessing wrongly, so you need to tell the engine what base to use (2 for binary, 8 for octal10 for decimal, 16 for hex, etc)
You have to use parseInt(a.substring(0,2),10);
parseInt take 2 parameters, the string to parse and the radix which is optionnal (but required with JSHint/JSLint).
If you don't pass the {radix{ parameter, parseInt will "choose" the best for the string you passed, so for the 08 string, it will take the octal radix and not the decimal one (the one you want).
TL;DR Always set the radix when using parseInt.
source: MDN
If you're dealing with time just to offer a different solution you could try doing it like this:
var clock = '07:30';
var time = {
hours: +clock.split(':')[0],
minutes: +clock.split(':')[1]
}

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

What do you think parseInt("08") will return? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Workarounds for JavaScript parseInt octal bug
Surprisingly it returns 0. Why? and what's the (proper) solution to get correct results?
Use a radix:
var x = parseInt("08", 10);
Some JavaScript implementations add a third numeral system to the two defined by the standard (decimal, the default; and hex, prefixed with 0x): Octal, prefixed with 0. This is non-standard but acknowledged as common in the latest spec.
Since 8 is not a valid octal digit, parseInt stops there, returning the value 0.
By explicitly using a radix, you tell parseInt not to try to figure out what numeral system is being used but instead to use the one you specify. Your instinct when typing parseInt should always be to specify the radix; not doing so leaves you open to oddities.
"08" mean 8 based number. You should specify second argument.
parseInt("08", 10)
#T.J. gave a great explanation for the behaviour you see. Another way to parse a number string is to use unary +:
var num = +"08";
From http://www.bennadel.com/blog/2012-Exploring-Javascript-s-parseInt-And-parseFloat-Functions.htm:
Strings that start with "0" are assumed to be base8 (octal).
From MDC - parseInt:
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.
And the example:
parseInt("08"); // 0, '8' is not an octal digit.
That is, since no radix was passed in and the string begins with 0 octal is assumed. Since 8 is not an octal digit it cannot be parsed.
Solution? Always provide a radix parameter:
parseInt("08", 10);
If you run it through jslint, it'll squawk at you for not including the radix parameter. Yes, the radix is optional, but probably should be included every time. A number starting with 0 is assumed to be octal unless otherwise specified.
var foo = parseInt("08", 10);
Number prefixed with "0" is octal number. 8 is invalid octal number. so the result is 0

Categories

Resources