JavaScript string and number conversion

209,946

Solution 1

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>

Solution 2

Step (1) Concatenate "1", "2", "3" into "123"

 "1" + "2" + "3"

or

 ["1", "2", "3"].join("")

The join method concatenates the items of an array into a string, putting the specified delimiter between items. In this case, the "delimiter" is an empty string ("").


Step (2) Convert "123" into 123

 parseInt("123")

Prior to ECMAScript 5, it was necessary to pass the radix for base 10: parseInt("123", 10)


Step (3) Add 123 + 100 = 223

 123 + 100


Step (4) Covert 223 into "223"

 (223).toString() 


Put It All Togther

 (parseInt("1" + "2" + "3") + 100).toString()

or

 (parseInt(["1", "2", "3"].join("")) + 100).toString()

Solution 3

r = ("1"+"2"+"3")           // step1 | build string ==> "123"
r = +r                      // step2 | to number    ==> 123
r = r+100                   // step3 | +100         ==> 223
r = ""+r                    // step4 | to string    ==> "223"

//in one line
r = ""+(+("1"+"2"+"3")+100);

Solution 4

These questions come up all the time due to JavaScript's typing system. People think they are getting a number when they're getting the string of a number.

Here are some things you might see that take advantage of the way JavaScript deals with strings and numbers. Personally, I wish JavaScript had used some symbol other than + for string concatenation.

Step (1) Concatenate "1", "2", "3" into "123"

result = "1" + "2" + "3";

Step (2) Convert "123" into 123

result = +"123";

Step (3) Add 123 + 100 = 223

result = 123 + 100;

Step (4) Convert 223 into "223"

result = "" + 223;

If you know WHY these work, you're less likely to get into trouble with JavaScript expressions.

Solution 5

You can do it like this:

// step 1 
var one = "1" + "2" + "3"; // string value "123"

// step 2
var two = parseInt(one); // integer value 123

// step 3
var three = 123 + 100; // integer value 223

// step 4
var four = three.toString(); // string value "223"
Share:
209,946
user366312
Author by

user366312

delete me.

Updated on March 11, 2020

Comments

  • user366312
    user366312 about 4 years

    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"

  • artlung
    artlung almost 15 years
    Best practice would be to add the radix parameter to the parseInt() function. so, parseInt(one, 10) assures that whatever you throw at it won't get misconverted.
  • annakata
    annakata almost 15 years
    I actually think this is extremely bad practice because it's fairly opaque as to waht's going on. Knowing that certain operations affect an implicit cast is a trick, and a good one to know, but it's not at all readable. Communication is everything.
  • Nosredna
    Nosredna almost 15 years
    I think it's important to know these things PRECISELY so you know what's going on when you read code. Much JavaScript is terse because it's transmitted as source, and small code can mean server cost reduction.
  • annakata
    annakata almost 15 years
    You should be achieving this through compression tools though, in this form it's optimisation at a very real cost of maintenance.
  • Nosredna
    Nosredna almost 15 years
    Still, knowing these things would help prevent the question in the first place, which was a lack of knowledge on how JavaScript deals with strings and numbers. It's a matter of intellectual curiosity. What happens when I add a number to a string? How does unary plus work? If you don't know the answers, you don't really know JavaScript, and these kind of questions will come up.
  • hotshot309
    hotshot309 over 12 years
    Nice, clear example. Also, kudos for good form--you should always specify the radix for the parseInt function.
  • hotshot309
    hotshot309 over 12 years
    Agreed. Otherwise, values starting with 0 will be seen as octal (base-8) numbers.
  • Robert Martin
    Robert Martin over 11 years
    Even more unexpected, values starting with 0 and then containing 8 or 9 will fail, leading to a return of 0. E.g., parseInt('034') = 28, and parseInt('09') = 0.
  • mcont
    mcont over 9 years
    Thanks for the fast string-->number conversion
  • Julix
    Julix over 7 years
    Any particular reason you put this in script tags?
  • artlung
    artlung over 7 years
    @Julix For novices in 2009, plopping into an html file to learn a basic concept. If I were answering this fresh today I might do it differently, but maybe not.
  • greene
    greene almost 7 years
    If you check it is a number or not then use parseInt(). For example, parseInt(" ") is NaN, but +" " is 0!
  • Nick Rice
    Nick Rice almost 7 years
    Relying on tricks based on language quirks like this can lead to real obscurity. eg "5"-0 does indeed result in the number 5, but "5"+0 results in the string "50". (Yes I know it's many years later and it's probably a bit sad I was even reading this.)
  • ArtOfWarfare
    ArtOfWarfare over 6 years
    Including the radix confused me and I scrolled on to another answer where it was explained. Edited in a quick explanation to be right at the point of confusion.
  • Cédric Guillemette
    Cédric Guillemette over 6 years
    @ArtOfWarfare Thanks, good edit. The radix was necessary at the time of this answer. These days, an argument can me made to leave it out. As of ES5, which all “modern” browsers and Node.js support, parseInt(<a string with only 0-9>) always uses base 10.
  • Justin Ohms
    Justin Ohms about 6 years
    fun fact.. in Netscape's original JavaScript (circa 1995) the default radix for parseInt was 8 (unless the string contained and 8 or a 9)