Convert string to number / Convert number to string in JavaScript

AID: 1642
  • Status: Published

5650 points

  • By
  • TypeTips/Tricks
  • Posted on2009-09-25 at 19:22:23

This EE article provides JavaScript examples of conversion from string to integer, string to floating-point, and number to string.  We'll also look at some related topics, including how to format numeric output with two decimal places, and one way to do right-justification of numeric text.

"" title="First... The Short Answer"]

//------------------ convert number to string
var n= 123;    // n is a number -- value is one hundred-twenty-three
var s= ''+n;   // s is a string with three characters -- value is '123'

//------------------ convert string to number
var s= '12 days';     // s is a string
var n= parseInt( s ); // n is a number -- value is twelve
                                  
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

Thus, the simplest technique for number-to-string is to let the string concatenation operator do it for you.  And the parseInt() function is the most reliable way to break out a numeric value that's at the start of a string (or is the entire string).


"" title="Automatic Conversion"]JavaScript will do most conversions for you automatically:

var n=1234;
alert(n);
alert( 'The value is: ' + n );
                                  
1:
2:
3:

Select allOpen in new window

The first example uses the fact that the alert function (or WScript.Echo) displays textual (string) data, so the parameter is converted automatically for you.  The second example uses the fact that concatenating a number to a string forces an automatic conversion.

However, there are cases where the built-in conversion might not work as hoped.  For instance,  

var nHundreds=1;
var nTens=2;
var nOnes=3;
alert( 'The answer is ' + nHundreds+nTens+nOnes  );  // The answer is 123
alert( 'The answer is ' + (nHundreds+nTens+nOnes) ); // The answer is 6 
alert( nHundreds+nTens+nOnes + ' is the answer' );   // 6 is the answer
var s= '7';;
alert( nHundreds+nTens+nOnes +s+ ' is the answer' ); // 67 is the answer
                                  
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window

These examples illustrate now certain automatic type-conversions are performed.    JavaScript's + operator will try to make the "sum" (the concatenation result of two operands) to be the same data type as the addend (the first operand).

In the second example (line5), the parentheses make the numeric calculation into a single number value, rather than three string values.  

The third example has three numeric values at the start, so it treats them as numbers when added.  Then it encounters a string, so it converts the addend (a number) into a string for string concatenation.

The fourth example is a bit more subtle.  The fourth item (variable s) is a one-character string.  One might think that JavaScript would convert it to a number so that it could be added to the previous numbers.  But a string datatype always trumps a numeric datatype, so adding s is a string concatenation -- not a numeric addition.



"" title="Explicit Conversion"]JavaScript provides operators that you can use to avoid any ambiguities that might crop up.  That is, rather than letting the language interpreter do an automatic conversion, you can force the datatype.

The toString() function outputs a string.  The parseInt() function outputs an integer number.  For instance:

var n1= 1;                 // a number
var n2= 2;                 // a number
alert( n1+n2 );            // shows 3 (a number)
alert( n1+n2.toString() ); // shows '12' (a string)

var s1= '1';               // a string
var s2= '2';               // a string
alert( s1+s2 );            // shows '12' (a string)
alert( parseInt(s1)+parseInt(s2) ); // shows 3 (a number)
                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window


Most textual strings that you need to convert will be composed of decimal digits.  But parseInt() will treat a string in the form 0xnnnn as a hexadecimal input value.   You can also explicitly select the numeric base using an optional second parameter (the radix).   Examples:

var s1='0xFF';  
alert( parseInt(s1) );    // shows 255

var s2='ffff';  
alert( parseInt(s2,16) ); // shows 65535

var s2='00000101';  
alert( parseInt(s2,2) );  // shows 5 (decimal value of binary 101 )  
                                  
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window

The last example converts a string of 0s and 1s (presumed to represent a binary -- base 2 --  value) into a decimal value; i.e., something more useful for human consumption.

Important notes about parseInt():
The parseInt() function discards any leading whitespace, then reads the string from left to right, stopping when it hits an unexpected character.    That can be very useful.  For instance, it lets you collect a numeric value at the start of a string without needing to know how many characters long it is:

var s= '   100%</div>'; // a snip of HTML
alert( parseInt(s) );   // shows 100 
                                  
1:
2:

Select allOpen in new window


But it considers a commas and periods (along with all other non-digit values) as delimiters (where it will stop parsing).  So,

var s1= '1,000,000.00'; 
alert( parseInt(s1) );   // shows 1 

var s2= '123.99'; 
alert( parseInt(s2) );   // shows 123 

var s3= '$123.99'; 
alert( parseInt(s3) );   // shows NAN (or 1.#QNAN)
                                  
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window

The last one is most problematic.  If the input string does not start with a valid digit (or whitespace followed by a valid digit), your output will look pretty ugly.  If you can't be sure that the string will parse into a valid numeric value, then use the isNaN() function:

var n= parseInt( s );
if ( isNaN(n) ) {
    ... s was invalid input, do something.  Don't display it.
}
                                  
1:
2:
3:
4:

Select allOpen in new window


Finally, if the text being parsed begins with a leading zero, it will be parsed as an octal number.  That's fine for values like 007, but it can lead to confusing results...

alert( parseInt('011') );     // shows 9
alert( parseInt('011',10) );  // shows 11
                                  
1:
2:

Select allOpen in new window

So it is advisable to use the radix parameter to avoid getting unexpected values.


"" title="String to Floating-Point"]Up until now, we've assumed that you are converting to an integer.  When your expected input value may contain a decimal point, you should use parseFloat().  For instance:

var s1= ' 12345.67 (low down payment)';
alert( parseFloat(s1) );   // shows 12345.67

var s2= ' 12345.00';
alert( parseFloat(s2) );   // shows 12345
                                  
1:
2:
3:
4:
5:

Select allOpen in new window


Notice that in the second example, we lose the "cents" -- if there is nothing but zeros after the decimal point (it's a whole number) then we may need to do some work to format it for output.   Fortunately, the most common need is covered by a standard JavaScript function, toFixed().  Just specify 2 decimal places, and your output will show dollars and cents as expected:

var s1= ' 12345.00';
var n1= parseFloat(s1);  // value is 12345
alert( n1.toFixed(2) );  // shows 12345.00

var n2= 12345.666;
alert( n2.toFixed(2) );  // shows 12345.67 <<= Note: rounded up
                                  
1:
2:
3:
4:
5:
6:

Select allOpen in new window



Format as U.S. Currency
As the final tip for this article, here is a little routine that I use when I need a fixed-width output of a dollars and cents value.  Pass in a number, and it outputs a string formatted as U.S. currency, with leading dollar sign, decimal point and two digits, commas separating thousands, millions, and billions, and it's padded with leading spaces so that columns of these formatted values will line up:

//---- outputs a string value: (spaces)$n,nnn.nn
function toDollars( nValue, nWide ) {
    var s= nValue.toFixed(2);
    for( j=6; j<15; j+=4 ) {  // insert commas
        if ( s.length > j ) { 
            s= s.substr(0,s.length-j)+','+ s.substr(s.length-j);
        }
    }
    s= '$'+s;  // leading dollar sign
    if ( !isNaN(nWide) ) { // parameter is present
        while( nWide > s.length ) {  // pad with leading spaces
            s=' '+s;
        }
    }
    return(s);
}
//usage example
var s= toDollars(1234567.88,15) +"\n";
  s += toDollars(     17.88,15) +"\n";
  s += toDollars(     0.888,15);
// output is:
//  $1,234,567.88
//         $17.88
//          $0.89
                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:

Select allOpen in new window



References:

JavaScript parseInt() Function
http://www.w3schools.com/jsref/jsref_parseInt.asp

JavaScript parseFloat() Function
http://www.w3schools.com/jsref/jsref_parseFloat.asp

JavaScript toString() Method
http://www.w3schools.com/jsref/jsref_tostring_number.asp

JavaScript toFixed() Method
http://www.w3schools.com/jsref/jsref_tofixed.asp

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
If you liked this article and want to see more from this author,  please click the Yes button near the:
      Was this article helpful?
label that is just below and to the right of this text.   Thanks!
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Asked On
2009-09-25 at 19:22:23ID1642
Tags

javascript

,

JScript

,

convert to string

,

convert to integer

,

convert to floating point

,

format currency

,

toFixed

,

parseInt

,

toString

Topic

JavaScript

Views
14164

Comments

Add your Comment

Please Sign up or Log in to comment on this article.

Loading Advertisement...

Top JavaScript Experts

  1. leakim971

    143,018

    Master

    6,600 points yesterday

    Profile
    Rank: Genius
  2. nap0leon

    118,795

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  3. chaituu

    85,750

    Master

    0 points yesterday

    Profile
    Rank: Sage
  4. COBOLdinosaur

    65,432

    Master

    0 points yesterday

    Profile
    Rank: Genius
  5. mplungjan

    54,450

    Master

    4,800 points yesterday

    Profile
    Rank: Genius
  6. StingRaY

    44,564

    0 points yesterday

    Profile
    Rank: Wizard
  7. tommyBoy

    36,500

    2,800 points yesterday

    Profile
    Rank: Sage
  8. ddayx10

    29,042

    0 points yesterday

    Profile
    Rank: Sage
  9. hielo

    24,230

    0 points yesterday

    Profile
    Rank: Savant
  10. mrh14852

    23,800

    0 points yesterday

    Profile
    Rank: Master
  11. HainKurt

    22,916

    2,000 points yesterday

    Profile
    Rank: Genius
  12. DaveBaldwin

    18,048

    2,000 points yesterday

    Profile
    Rank: Genius
  13. mroonal

    17,300

    1,500 points yesterday

    Profile
    Rank: Sage
  14. kozaiwaniec

    15,800

    2,000 points yesterday

    Profile
    Rank: Master
  15. Ray_Paseur

    15,448

    0 points yesterday

    Profile
    Rank: Savant
  16. sjklein42

    13,800

    0 points yesterday

    Profile
    Rank: Sage
  17. Zvonko

    13,376

    0 points yesterday

    Profile
    Rank: Genius
  18. darren-w-

    12,301

    0 points yesterday

    Profile
    Rank: Wizard
  19. zappafan2k2

    11,888

    0 points yesterday

    Profile
    Rank: Guru
  20. Badotz

    11,830

    1,680 points yesterday

    Profile
    Rank: Genius
  21. maeltar

    11,732

    0 points yesterday

    Profile
    Rank: Guru
  22. tagit

    11,325

    0 points yesterday

    Profile
    Rank: Genius
  23. atique_ansari

    10,900

    0 points yesterday

    Profile
    Rank: Master
  24. gman84

    10,788

    0 points yesterday

    Profile
  25. tamer82

    10,664

    0 points yesterday

    Profile

Hall Of Fame