Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript string and number conversion

How can I do the following in JavaScript?

  1. Concatenate "1", "2", "3" into "123"

  2. Convert "123" into 123

  3. Add 123 + 100 = 223

  4. Covert 223 into "223"

like image 590
user366312 Avatar asked Jun 09 '09 16:06

user366312


People also ask

What is the fastest way to convert number to string in JavaScript?

Adding empty string to the number value will convert the data to string is one of the simplest way to do the job. It is also considered to be faster than the above two when it comes to performance.

Is string a number JavaScript?

In JavaScript, a built-in method isNaN() evaluates the string in such a way that if the passed string is a number. This built-in function of JavaScript returns a true or false output based on the passing string. Furthermore, the “+” operator is employed to check the string by converting the string into a number.

How do I parseInt a string in JavaScript?

To convert a string to an integer parseInt() function is used in javascript. parseInt() function returns Nan( not a number) when the string doesn't contain number. If a string with a number is sent then only that number will be returned as the output. This function won't accept spaces.


1 Answers

You want to become familiar with parseInt() and toString().

And useful in your toolkit will be to look at a variable to find out what type it is—typeof:

<script type="text/javascript">     /**      * print out the value and the type of the variable passed in      */      function printWithType(val) {         document.write('<pre>');         document.write(val);         document.write(' ');         document.writeln(typeof val);         document.write('</pre>');     }      var a = "1", b = "2", c = "3", result;      // Step (1) Concatenate "1", "2", "3" into "123"     // - concatenation operator is just "+", as long     //   as all the items are strings, this works     result = a + b + c;     printWithType(result); //123 string      // - If they were not strings you could do     result = a.toString() + b.toString() + c.toString();     printWithType(result); // 123 string      // Step (2) Convert "123" into 123     result = parseInt(result,10);     printWithType(result); // 123 number      // Step (3) Add 123 + 100 = 223     result = result + 100;     printWithType(result); // 223 number      // Step (4) Convert 223 into "223"     result = result.toString(); //     printWithType(result); // 223 string      // If you concatenate a number with a      // blank string, you get a string         result = result + "";     printWithType(result); //223 string </script> 
like image 188
artlung Avatar answered Sep 17 '22 17:09

artlung