10

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
3
  • 3
    Never use new Number(), if any, use Number(). It depends on what kind of input you consider is valid. E.g. parseFloat will accept "123foo" and return 123 but Number (or the unary +) will return NaN. Commented Jul 23, 2012 at 13:43
  • Yes good point: you can use the Number() constructor as a plain function though. Commented Jul 23, 2012 at 13:55
  • Possible duplicate of Convert a string to an integer? Commented Aug 19, 2019 at 11:33

4 Answers 4

18

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.

Sign up to request clarification or add additional context in comments.

11 Comments

what do you think about +x?
@m.abbas well it's probably equivalent to Number() but personally I would stay away from it as it's "syntactically fragile" (I just made that term up). That's just me being paranoid however.
Really? I love + :) The behaviour is well defined but it might not be obvious to everyone what it means/does (similar to ~~).
@FelixKling yes but as I note in my amendment it scares me because + is so crazy. Just a personal quirk I guess.
@Pointy The benefit of using + is the speed, as is shown in my answer's link.
|
6

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.

10 Comments

Explicit, readable code is usually better (unless it's overly verbose). Terse hacks like ~~x limit the readability of your code and should be avoided unless you're really tight on space for some reason (like a short JavaScript coding compo). And in your case ~~x is not even a valid solution because it gives you an integer.
@Hans Z mmm...and ~~ is not confusing? I guess "confusing" depends on the developer...
The only problem I have with parseFloat() is that it ignores non-numeric characters after the number. Thus a string that starts with digits but then ends with random other characters can still be parsed, and it won't be a NaN. For some applications that may be OK of course.
@al0neevenings Why don't you try and see with a few simple samples? Just write this in your JS console, or go to jsfiddle.net to experiment: parseFloat("-42.42")
Like I said, it would be my personal preference, but +x is shorter and there's nothing wrong with using it. (Using it in parentheses (+x) would solve the syntax issue anyway, and that's still shorter than Number(x) :-)
|
3

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

2 Comments

If you the isNumeric test, the efficiency of +x will become moot :) Maybe a isNaN(num) check after the conversion is better.
@AtesGoral What you suggest, is not proved (I mean isNaN), what I have posted is already proved.So I will choose the reliable way.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.