javascript parseInt error conversion [duplicate] - javascript

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]
}

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

Why does parseFloat(027) equals 23 [duplicate]

This question already has answers here:
parseInt("010", 10); vs. parseInt(010, 10);
(2 answers)
Closed 8 years ago.
I tested it in the chrome console and also in IE11.
parseFloat(27) => 27
parseFloat('27') => 27
parseFloat('027') => 27
but
parseFloat(027) => 23
parseFloat(0027) => 23
I guess is understanding it as an octal, but I didn't find any reference to that here
Since I'm using it to secure a number which is a user input, how can I make certain that even with the preceding 0 it gets handled as a float?
"027" is the way you specify 27 octal in source code. Since you aren't going to let a user input your source code, there's nothing special you need to do.
parseFloat doesn't understand octal:
> parseFloat('027')
27
The problem is that you're feeding it a number, rather than a string. 027 is an octal numeric literal that evaluates to 23; parseFloat doesn't know it ever looked like 027. As long as you make sure to pass a string to the function, you shouldn't have any octal problems.
Why does parseFloat(027) equals 23
The argument to parseFloat() is a string value, so a cast is performed on anything that's not a string; literal numbers such as 0x20 or 027 are normalized to the decimal system first.
That means parseFloat(027) is actually parseFloat('23').
how can I make certain that even with the preceding 0 it gets handled as a float?
By making sure the value you're passing to parseFloat() is a string value, because leading zeroes have no special meaning in parseFloat() (and parseInt() with a radix of 10).
It's interpreting the input as octal. See here. If you enter '027' in the "Octal" field you'll see "23" output in the "Decimal" field.

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.

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