Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parseInt alternative

Firstly - my description ;)

I've got a XmlHttpRequests JSON response from the server. MySQL driver outputs all data as string and PHP returns it as it is, so any integer is returned as string, therefore:

Is there any fast alternative (hack) for parseInt() function in JS which can parse pure numeric string, e.g.

var foo = {"bar": "123"};
...
foo.bar = parseInt(foo.bar); // (int) 123
like image 467
shfx Avatar asked Feb 27 '09 12:02

shfx


People also ask

What can I use instead of parseInt?

parseFloat( ) parseFloat() is quite similar to parseInt() , with two main differences. First, unlike parseInt() , parseFloat() does not take a radix as an argument. This means that string must represent a floating-point number in decimal form (radix 10), not octal (radix 8) or hexadecimal (radix 6).

Should I parseInt or number?

Since the method could be implemented differently in different versions of JavaScript and browsers, it's recommended to pass the radix number. Trim the spaces before parsing the number. To avoid the similar situations, you should remove all spaces before parsing: parseInt(value.

What is the opposite of parseInt?

toString() method when called on a number is the opposite of parseInt, meaning it converts the decimal to any number system between 2 and 36.

What does number parseInt () do?

The Number. parseInt() method parses a string argument and returns an integer of the specified radix or base.


1 Answers

To convert to an integer simply use the unary + operator, it should be the fastest way:

var int = +string;

Conversions to other types can be done in a similar manner:

var string = otherType + "";
var bool = !!anything;

More info.

like image 124
Aistina Avatar answered Sep 20 '22 23:09

Aistina