Behavior difference between parseInt() and parseFloat() [duplicate] - javascript

This question already has answers here:
Javascript parseInt() with leading zeros
(7 answers)
Closed 4 years ago.
Why is this behavior difference between parseInt() and parseFloat()?
I have a string that contains 08 in it.
When I write this code:
alert(hfrom[0]);
alert(parseInt(hfrom[0]));
alert(parseFloat(hfrom[0]));
The following output is generated:
08
0
8
Why does parseInt and parseFloat return two different results in this case?

parseInt() assumes the base of your number according to the first characters in the string. If it begins with 0x it assumes base 16 (hexadecimal). Otherwise, if it begins with 0 it assumes base 8 (octal). Otherwise it assumes base 10.
You can specify the base as a second argument:
alert(parseInt(hfrom[0], 10)); // 8
From MDN (linked above):
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).

you should always include the radix param with parseInt() ex parseInt('013', 10) otherwise it can convert it to a different numeric base:
parseInt('013') === 11
parseInt('013', 10) === 13
parseInt('0x13') === 19

Related

Javascript Eval error with numbers having leading zeroes [duplicate]

This question already has answers here:
Number with leading zero in JavaScript
(3 answers)
Closed 5 years ago.
If I use the code:
string = '010';
write = eval(string);
document.write(write)
I get 8 written on the page. Why?
This happens even if 010 isn't a string.
Because 010 is parsed as octal. Javascript treats a leading zero as indicating that the value is in base 8.
Similarly, 0x10 would give you 16, being parsed in hex.
If you want to parse a string using a specified base, use parseInt:
parseInt('010', 8); // returns 8.
parseInt('010',10); // returns 10.
parseInt('010',16); // returns 16.
Prefixing a number with an 0 means it's octal, i.e. base 8. Similar to prefixing with 0x for hexadecimal numbers (base 16).
Use the second argument of parseInt to force a base:
> parseInt('010')
8
> parseInt('010', 10)
10
If you'd like to output the string 010 to the document, you can wrap the value in quotation marks:
var octal = eval('"010"');
typeof octal; // "string"
If you want to parse an integer or understand octals, read the other answers.

lint warning: parseInt missing radix parameter [duplicate]

This question already has answers here:
JSLint says "missing radix parameter"
(11 answers)
Closed 9 years ago.
I have the following code that gives the warning described in the title:
year: parseInt(dateParts[0]),
......................^
Any help is much appreciated
See the manual for parseInt; it takes 2 arguments. The second one tells it which number base you want to use. This is almost always going to be 10 (decimal).
parseInt(dateParts[0],10)
If you don't specify it, then it will be inferred from the data.
If radix is undefined or 0 (or absent), JavaScript assumes the following:
If the input string begins with "0x" or "0X", radix is 16
(hexadecimal) and the remainder of the string is parsed.
If the input string begins with "0", radix is eight (octal) or 10
(decimal). Exactly which radix is chosen is implementation-dependent.
ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers
support this yet. For this reason always specify a radix when using
parseInt.
If the input string begins with any other value, the radix is 10
(decimal).
Some years after I wrote the above, things have changed. Now:
The ECMAScript 5 specification of the function parseInt no longer allows implementations to treat Strings beginning with a 0 character as octal values. Many implementations have adopted this behavior as of 2021.
… but you still should use a radix, at least for browser side code, because not all implementations have caught up.

Why won't parseInt work on a large number with leading 0's? [duplicate]

This question already has answers here:
How to parseInt a string with leading 0
(6 answers)
Closed 8 years ago.
avar = "0000013482000000";
t = parseInt(avar);
When I run that, t is 92 for some reason. If I remove the leading 0's, then it works just fine. Why would that be?
Try this:
avar = "0000013482000000";
t = parseInt(avar,10);
Some browsers might assume that it is an octal number if the string starts with 0.
However, ,10 is not required in modern browsers with new ECMAScript standards because they will always be considered as decimal unless specified or starts with 0x (hexadecimal).
Chrome is one of those browsers that has a default radix of 10.
Reference: ECMAScript Language Specification Page 104
The parseInt function produces an integer value dictated by interpretation of the contents of the string
argument according to the specified radix. Leading white space in string is ignored. If radix is undefined or 0,
it is assumed to be 10 except when the number begins with the character pairs 0x or 0X, in which case a radix
of 16 is assumed. If radix is 16, the number may also optionally begin with the character pairs 0x or 0X.
Use the second parameter (radix):
t = parseInt(avar, 10);
To specify that the number should be parsed in base 10.
From the MDN docs:
If radix is undefined or 0 (or absent), JavaScript assumes the following:
If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
If the input string begins with any other value, the radix is 10 (decimal).
And in reference to ECMAScript 5:
The parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading white space in string is ignored. If radix is undefined or 0, it is assumed to be 10 except when the number begins with the character pairs 0x or 0X, in which case a radix of 16 is assumed. If radix is 16, number may also optionally begin with the character pairs 0x or 0X.
Reference:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt
Parsing a number with leading zeros causes the number to be treated as octal. To override this you need to set the radix parameter of parseInt to 10 (base 10 as opposed to base 8).
parseInt assumes octal notation if you have a leading zero, so you want to pass in a radix as the second parameter, telling the function to parse the string as a base 10 int.
parseInt(avar, 10)
should fix it.

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

Javascript parseInt gives very unexpected results [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Workarounds for JavaScript parseInt octal bug
I'm parsing a string to check if it's a date, and by chance we now discovered that my method doesn't work for dates in august or september. This is what I do (the input isn't really hard-coded, obviously, but for brevity...):
var str = '2010-08-26 14:53';
var data = str.split(' '); // ['2010-08-26', '14:53']
var date = data[0].split('-'); // ['2010', '08', '26]
var time = data[1].split(':'); // ['14', '53']
var yyyy = parseInt(date[0]); // 2010
// THIS IS WHERE STRANGE THINGS HAPPEN:
var MM = parseInt(date[1]); // 0 - not 08 or 8, as expected!
console.log(date[1]); // prints "08" (with quotes)
console.log(date[1].toString()); // prints 08 (no quotes)
console.log(parseInt(date[1].toString())); // prints 0 (!)
This problem arises for august and september, and for the 8th and 9th every month - that is, when either "08" or "09" is being parsed to integer, 0 is returned instead of 8 or 9. The code works for both lower (e.g. "07") and higher (e.g. "10") integers (at least within expected date ranges...)
What am I doing wrong?
Use
parseInt(date[1], 10)
to make sure the string is interpreted as base 10 (decimal).
Otherwise, it is interpreted as base 8 (octal) if it starts with "0", or as base 16 (hexadecimal) if it starts with "0x".
In fact, you should always include the base argument to avoid these kinds of bugs.
That's because numbers that start with 0 are treated as octal numbers and "08" is not an octal so 0 is returned.
Read this: http://mir.aculo.us/2010/05/12/adventures-in-javascript-number-parsing/
The parseInt() function has the second optional radix parameter. If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)
So in your case it assumes the octal numbers. Change to var MM = parseInt(date[1], 10); and it will work
It sounds like your date is being parsed as hex - the leading zero is doing this.
Because the hex and decimal representations are the same for 0-7 it 'works', but 8 and 9 get incorrectly converted.
Use
parseInt(date[1], 10)
To specify the base explicitly.

Categories

Resources