Javascript – Convert Number to String and Vice Versa

Convert String to Number using parseFloat() or parseInt()

/* parseFloat() */
parseFloat('1.45kg')  // 1.45
parseFloat('77.3')    // 77.3
parseFloat('077.3')   // 77.3
parseFloat('0x77.3')  // 0
parseFloat('.3')      // 0.3
parseFloat('0.1e6')   // 100000

/* parseInt() */
parseInt('123.45')  // 123
parseInt('77')      // 77
parseInt('077',10)  // 77
parseInt('77',8)    // 63  (= 7 + 7*8)
parseInt('077')     // 63  (= 7 + 7*8)
parseInt('77',16)   // 119 (= 7 + 7*16)
parseInt('0x77')    // 119 (= 7 + 7*16)
parseInt('099')     // 0 (9 is not an octal digit)
parseInt('99',8)    // 0 or NaN, depending on the platform
parseInt('0.1e6')   // 0
parseInt('ZZ',36)   // 1295 (= 35 + 35*36)


 
 

Convert Number to String

Actually you could treat a number variable as a string variable. For example, you could concatenate a string with number. But if you really want to convert a number to string, just concatenate it with an empty string.

a = a+'' // This converts a to string
b += ''  // This converts b to string

 

You could find more common Javascript FAQ @ javascripter.net

Done =)

Reference: Converting Strings to Numbers

Advertisements

2 thoughts on “Javascript – Convert Number to String and Vice Versa”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s