Default parseInt radix to 10

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);
}

Introduction

First off, the parseInt method assumes the followingsource:

  • if it starts with 0x - then it is hex.
  • if it starts with 0 - then it is octal
  • else it is decimal

So you could go with the solution, never start with 0 ;)

Solution

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:

  • if it starts with 0x - then it is hex
  • else it is decimal

The only way to get octal then is to set the radix parameter to 8.

Problem

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.

Chrome 19 versus IE 10 Release Preview

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 :(


I assume you mean parseInt('014'), not parseInt(014).

If you really want to replace parseInt with your own function (I strongly discourage this), I guess you could do it with something like:

(function(_parseInt)
{   
    parseInt = function(string, radix)
    {    return _parseInt(string, radix || 10);
    };

})(parseInt);

Tags:

Javascript