One of the bad parts of JavaScript is that if you use parseInt with something that begins with 0, then it could see the number as a octal.
i = parseInt(014); // Answer: 12
Q: How can I redefine parseInt so that it defaults to radix 10? I'm assuming you would use the prototype method.
Edit:
Maybe I should do this:
$.fn.extend({
parseInt:function(X) {
return parseInt(X,10);
}
});
By default radix is 10 (decimal).
The parseInt method parses a value as a string and returns the first integer. A radix parameter specifies the number system to use: 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal.
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .
You can use parseInt() by inputting a decimal or string in the first argument and then defining a radix. If the first argument cannot be converted into a number, parseInt() will return NaN .
If you store a reference to the original parseInt
function, you can overwrite it with your own implementation;
(function () {
var origParseInt = window.parseInt;
window.parseInt = function (val, radix) {
if (arguments.length === 1) {
radix = 10;
}
return origParseInt.call(this, val, radix);
};
}());
However, I strongly recommend you don't do this. It is bad practise to modify objects you don't own, let alone change the signature of objects you don't own. What happens if other code you have relies on octal being the default?
It will be much better to define your own function as a shortcut;
function myParseInt(val, radix) {
if (typeof radix === "undefined") {
radix = 10;
}
return parseInt(val, radix);
}
First off, the parseInt
method assumes the followingsource:
So you could go with the solution, never start with 0 ;)
With ECMA-262 (aka EcmaScript 5, aka JavaScript version 5) one of the new features is strict mode which you turn on with "use strict"
When you opt-in to strict mode the rules changesource:
The only way to get octal then is to set the radix parameter to 8.
At the time of writing the support for ECMAScript 5 isn't consistent across all browsers and so some browsers do not support it at all, which means the solution isn't useful to them. Other browsers implementations are broken, so even though the proclaim it supports it, they do not.
The below image is of IE 10 release preview versus Chrome 19 - where IE runs it correctly but Chrome doesn't.
The easy way to check your browser is to go to: http://repl.it/CZO# You should get 10, 10, 8, 10, 16 as the result there, if so great - if not your browser is broken :(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With