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)
.?
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)
.?
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)
.
var origParseInt = parseInt;
parseInt = function(n) {
return origParseInt(n, 10);
}
And it works!
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
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
.