Om3ga
Om3ga

Reputation: 32823

convert string to a number in javascript

I want to parse a user input which contains longitude and latitude. What I want to do is to coerce a string to a number, preserving its sign and decimal places. But what I want to do is to display a message when user's input is invalid. Which one should I follow

parseFloat(x)

second

new Number(x)

third

~~x

fourth

+x

Upvotes: 10

Views: 12500

Answers (4)

M. Ahmad Zafar
M. Ahmad Zafar

Reputation: 4939

This is the code I would write to repeatedly take input until the correct one is obtained.

var d;

do {
    d = prompt("Enter a number");
    d = new Number(d);
} while( isNaN(d) );

document.write( d );

Note: new Number(d) will always give NaN if any character is non-numeric while parseFloat(d) will ignore trailing invalid characters.

Upvotes: 1

Engineer
Engineer

Reputation: 48793

To test whether input is number, use this:

function isNumeric(obj){
    return !isNaN( parseFloat(obj) ) && isFinite( obj );
}

To cast String to Number, use + ,it's the fastest method:

the unary + operator also type-converts its operand to a number and because it does not do any additional mathematical operations it is the fastest method for type-converting a string into a number

So overall, probably you need this:

if(!isNumeric(inputValue)){
    alert('invalid number');
}else{
    var num = +inputValue;
}

isNumeric borrowed from jQuery

Upvotes: 3

Pointy
Pointy

Reputation: 413682

I'd use Number(x), if I had to choose between those two, because it won't allow trailing garbage. (Well, it "allows" it, but the result is a NaN.)

That is, Number("123.45balloon") is NaN, but parseFloat("123.45balloon") is 123.45 (as a number).

As Mr. Kling points out, which of those is "better" is up to you.

edit — ah, you've added back +x and ~~x. As I wrote in a comment, +x is equivalent to using the Number() constructor, but I think it's a little risky because of the syntactic flexibility of the + operator. That is, it'd be easy for a cut-and-paste to introduce an error. The ~~x form is good if you know you want an integer (a 32-bit integer) anyway. For lat/long that's probably not what you want however.

Upvotes: 18

Ateş Göral
Ateş Göral

Reputation: 140032

The first one is better. It is explicit, and it is correct. You said you want to parse floating point numbers. ~~x will give you an integer.

Upvotes: 6

Related Questions