Create integer literal for decimal, octal, hexadecimal

Description

To support the various types of numbers, there are several different number literal formats.

Integers can be represented as either octal (base 8) or hexadecimal (base 16) literals.

Decimal

The most basic number literal format is decimal integer, which can be entered directly as shown here:


var intNum = 105;         //integer
console.log(intNum);

Octal

For an octal literal, the first digit must be a zero (0) followed by a sequence of octal digits (numbers 0 through 7).

If a number out of this range is detected in the literal, then the leading zero is ignored and the number is treated as a decimal.


var octalNum1 = 070;     //octal for 56
console.log(octalNum1);// ww  w  . j  a v  a 2s  .  c o  m
var octalNum2 = 079;     //invalid octal - interpreted as 79
console.log(octalNum2);
var octalNum3 = 08;      //invalid octal - interpreted as 8
console.log(octalNum3);

Octal literals are invalid when running in strict mode and will throw a syntax error.

The code above generates the following result.

Hexadecimal

To create a hexadecimal literal, you start the first two characters with 0x or 0X, followed by any number of hexadecimal digits (0 through 9, and A through F).

Letters may be in uppercase or lowercase. Here's an example:


var hexNum1 = 0xA;       //hexadecimal for 10
console.log(hexNum1);
var hexNum2 = 0x1f;      //hexedecimal for 31
console.log(hexNum2);

Numbers created using octal or hexadecimal format are treated as decimal numbers in all arithmetic operations.

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions