Is parseInt with radix 10 useless?

Y

Yaffle

Using "+(x)" is better, than parseInt(x,10) ?!?
(if string "x" contains only decimal numbers)
 
L

Lasse Reichstein Nielsen

Yaffle said:
Using "+(x)" is better, than parseInt(x,10) ?!?
(if string "x" contains only decimal numbers)

Define "better".

They give the same result.
"parseInt" is marginally more readable, while "+" is slightly
faster (but unless it is used in a tight loop, it's not going
to make a difference).

Personally I prefer "Number(x)" for readability.

/L
 
D

Dr J R Stockton

In comp.lang.javascript message <nZ6dnabFuMXM_QzXnZ2dnUVZ8qSdnZ2d@bright
Suppose, for example, I have a function range() that requires a number
as its argument. I could convert the argument inside range().

Or I could write
range(+x);
when I call range. I like this. It's saying that 'x' might be a
string, and I'll be converting it to a number.

To discuss the choice meaningfully, one needs to consider the
circumstances.

I have a function :
function GetNum(Ctrl) { // input for expressions, allows spaces
return +eval(Ctrl.value.replace(/[ ]/g, '')) }

which I use for some inputs to calculations. A routine requiring input
in kilometres, for example, can call it, and then the metrically-
challenged can enter 1.609*Miles. If Ctrl is a textarea, a user can
insert, at need, a considerable chunk of code.

On the other hand, a goods-ordering application may better be done using
a RegExp to check that the control has a reasonable number of decimal
digits, then nothing else. Then unary + can again be used.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,089
Messages
2,570,602
Members
47,223
Latest member
smithjens316

Latest Threads

Top