Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to a number in javascript

Tags:

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
like image 310
Om3ga Avatar asked Jul 23 '12 13:07

Om3ga


People also ask

Can you convert a string into a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System.Convert class.

What is number () in JavaScript?

Number encoding The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to the stored number's magnitude and precision.

How can I extract a number from a string in JavaScript?

The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).


2 Answers

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.

like image 131
Pointy Avatar answered Sep 29 '22 09:09

Pointy


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.

like image 20
Ates Goral Avatar answered Sep 29 '22 11:09

Ates Goral