Javascript type cast








Number()

Number() can be used on any data type. And it performs conversions based on these rules:

ParameterNumber Function Returns
Boolean true1
Boolean false0
null0
undefinedNaN
Empty string("")0
String with only number, for example "123"123
String with only number and plus sign, for example "+123"123
String with only number and minus sign, for example "-123"-123
Leading zeros are ignored, for example "0123"123
Leading zeros are ignored, for example "+0123"123
Leading zeros are ignored, for example "-0123"-123
String with valid floating-point format, such as "1.1"1.1
String with valid floating-point format, such as "+1.1"1.1
String with valid floating-point format, such as "-1.1"-1.1
Leading zeros are ignored, such as "01.1"1.1
String with hexadecimal format, "0xf"15
String with hexadecimal format, "-0xf"-15
String with not a number value, for example "asdf"NaN
objectsthe valueOf() method is called and the returned value is converted

var num1 = Number("Hello world!");  //NaN
console.log(num1);/*from   ww w. j  av  a  2s .c  o m*/
var num2 = Number("");              //0
console.log(num2);
var num3 = Number("000011");        //11
console.log(num3);
var num4 = Number(true);            //1
console.log(num4);

console.log(Number("-123"));
console.log(Number("+123"));   //123
console.log(Number("-0123"));  //-123
console.log(Number("0xf"));    //15
console.log(Number("-0xf"));   //-15
console.log(Number("asdf"));   // NaN

The code above generates the following result.

The unary plus operator works the same as the Number() function.





parseInt()

parseInt() function examines the string to see if it matches a number pattern.

parseInt() uses the following rules to convert string to an integer.

  • The parseInt() function ignores leading white space and it checks the string character by character.
  • If this first non-white space character isn't a number, the minus sign, or the plus sign, parseInt() returns NaN.
  • The parseInt() function returns NaN for empty string, while Number() function returns 0.
  • If the first character is a number, plus, or minus, then the checking continues until the end of the string is reached or a non numeric character is found. For instance, "1234asdf" is converted to 1234 because "asdf" is ignored.
  • When the string begins with "0x", it is interpreted as a hexadecimal integer.
  • If a string begins with "0" followed by a number, it is interpreted as an octal value.

var num1 = parseInt("1234blue");    //1234
console.log(num1);// w  ww.  j  a  va2  s. c  o m
var num2 = parseInt("");            //NaN
console.log(num2);
var num3 = parseInt("0xA");         //10 - hexadecimal
console.log(num3);
var num4 = parseInt(22.5);          //22
console.log(num4);
var num5 = parseInt("70");          //70 - decimal
console.log(num5);
var num6 = parseInt("0xf");         //15 - hexadecimal
console.log(num6);
//56 (octal) in ECMAScript 3, 0 (decimal) in ECMAScript 5
var num = parseInt("070");
console.log(num);

The code above generates the following result.





parseInt() with radix

parseInt() provides a second argument: the radix.

For hexadecimal format, the radix is 16.


console.log(parseInt("0xAE", 16));

The code above generates the following result.

The leading "0x" is not necessary by providing the hexadecimal radix:

console.log(parseInt("AE", 16));
var num2 = parseInt("AF");            //NaN
console.log(num2);

The code above generates the following result.

Most of the time you'll be parsing decimal numbers, so it's good to always include 10 as the second argument.

var num1 = parseInt("10", 2);         //2 - parsed as binary
console.log(num1);
var num2 = parseInt("10", 8);         //8 - parsed as octal
console.log(num2);
var num3 = parseInt("10", 10);        //10 - parsed as decimal
console.log(num3);
var num4 = parseInt("10", 16);        //16 - parsed as hexadecimal
console.log(num4);

parseFloat()

parseFloat() uses the following rules to convert string to float point value.

  • parseFloat() function looks at each character starting in position 0.
  • It continues to parse the string until it reaches either the end of the string or a character that is invalid in a floating-point number.
  • A decimal point is valid the first time it appears, but a second decimal point is invalid and the rest of the string is ignored, resulting in "12.34.5" being converted to 12.34.
  • parseFloat() always ignores initial zeros.
  • It will recognize floating-point with e-notation.
  • Hexadecimal numbers always become 0.
  • Because parseFloat() parses only decimal values, there is no radix mode.
  • If the string represents a whole number (2 or 2.0), parseFloat() returns an integer.

var num1 = parseFloat("1234blue");    //1234 - integer
console.log(num1);/*  ww w  .  ja  v  a 2s  .  c  o  m*/
var num2 = parseFloat("0xA");         //0
console.log(num2);
var num3 = parseFloat("22.5");        //22.5
console.log(num3);
var num4 = parseFloat("22.34.5");     //22.34
console.log(num4);
var num5 = parseFloat("0908.5");      //908.5
console.log(num5);
var num6 = parseFloat("3.125e7");     //31250000
console.log(num6);

The code above generates the following result.

Convert to String

There are two ways to convert a value into a string. 
  • toString() method from each value
  • String() cast function

toString()

toString() method returns the string equivalent of the value.

The toString() method is available on values that are numbers, Booleans, objects, and strings. If a value is null or undefined, this method is not available.


var age = 11; 
var aString = age.toString();         //the string "11" 
var found = true; 
var anotherString = found.toString(); //the string "true" 

console.log(anotherString);

The code above generates the following result.

Number toString()

toString() on a number value accepts a single argument: the radix.

By passing in a radix, toString() can output the value in binary, octal, hexadecimal, or any other valid base:


var num = 10;
console.log(num.toString());       //"10"
console.log(num.toString(2));      //"1010"
console.log(num.toString(8));      //"12"
console.log(num.toString(10));     //"10"
console.log(num.toString(16));     //"a"

The default is the same as providing a radix of 10.

The code above generates the following result.

String()

String() casting function is useful for null or undefined value. The String() function follows these rules:

ValueReturns
value with toString() methodcalled toString without arguments
null"null" string
undefined"undefined" string

Example:Four values are converted into strings: a number, a Boolean, null, and undefined. The result for the number and the Boolean are the same as if toString() were called.


var value1 = 10;
var value2 = true;
var value3 = null;
var value4;
/*w  ww.ja va  2 s  .c  o  m*/
console.log(String(value1));     //"10"
console.log(String(value2));     //"true"
console.log(String(value3));     //"null"
console.log(String(value4));     //"undefined"

Because toString() isn't available on "null" and "undefined", the String() method simply returns literal text for those values.

You can convert a value to a string by adding an empty string ("") to that value using the plus operator.

The code above generates the following result.