-1

I do not want use each and every time parseInt('08', 10) for each string to integer conversion,

Can we modify parseInt method, so that i can use only parseInt('08') instead of parseInt('08', 10).?

Niks Jain
  • 1,617
  • 5
  • 27
  • 53

3 Answers3

5

Instead of modifying the built-in function parseInt, you can define your own function like this:

function prseInt(n)
{
    return parseInt(n, 10);
}

And replace all the occurences of parseInt(n, 10) you have used in your app with prseInt(n).

Fine, if you still wanna redefine, you can do this:

var origParseInt = parseInt;
parseInt = function(n) {
     return origParseInt(n, 10);
}

And it works!

Fiddle: http://jsfiddle.net/QKKwv/

Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

Use simply a + operator in front of your string, to perform a type coercion (and no need to call parseInt())

var str = "08";
var num = +str;

console.log(num, typeof num);  // 8, number
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
0

parseInt(xx) (ie, without the radix parameter) will work perfectly fine 99% of the time, what it will do is attempt to guess what base you are after.

For a single number like 8 it will correctly guess basse10 and give you integer 8. The problem is a string like 08 it will guess what you want is octal, and converting "08" to octal returns zero.

You should ALWAYS be providing the radix parameter whenever using parseInt.

Community
  • 1
  • 1
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • Yeh..you are abs'ly right, but can't we modify built-in method, so we could use everytime parseInt(value) instead of parseInt(value, radix)? – Niks Jain Oct 12 '12 at 07:45
  • 1
    You *can* use `parseInt(value)` as I explained - so long as you understand the behaviour. If the `value` is ever going to be prefixed `0` it will convert it to Octal. And no, you cannot modify a built-in method, otherwise it wouldnt be "built-in". – Jamiec Oct 12 '12 at 07:46