JavaScript Numbers


JavaScript has only one type of number.

Numbers can be written with, or without decimals.


JavaScript Numbers

JavaScript numbers can be written with, or without decimals:

Example

var x = 34.00;    // A number with decimals
var y = 34;       // A number without decimals

Extra large or extra small numbers can be written with scientific (exponent) notation:

Example

var x = 123e5;    // 12300000
var y = 123e-5;   // 0.00123

JavaScript Numbers are Always 64-bit Floating Point

Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.

JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.

This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:

Value (aka Fraction/Mantissa) Exponent Sign
52 bits (0 - 51)  11 bits (52 - 62) 1 bit (63)

Precision

Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.

Example

var x = 999999999999999;   // x will be 999999999999999
var y = 9999999999999999;  // y will be 10000000000000000
Try it Yourself »

The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:

Example

var x = 0.2 + 0.1;         // x will be 0.30000000000000004
Try it yourself »

To solve the problem above, it helps to multiply and divide:

Example

var x = (0.2 * 10 + 0.1 * 10) / 10;       // x will be 0.3
Try it Yourself »

Hexadecimal

JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.

Example

var x = 0xFF;             // x will be 255
Try it Yourself »
Note Never write a number with a leading zero (like 07).
Some JavaScript versions interpret numbers as octal if they are written with a leading zero.

By default, Javascript displays numbers as base 10 decimals.

But you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).

Example

var myNumber = 128;
myNumber.toString(16);     // returns 80
myNumber.toString(8);      // returns 200
myNumber.toString(2);      // returns 10000000
Try it Yourself »

Infinity

Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.

Example

var myNumber = 2;
while (myNumber != Infinity) {          // Execute until Infinity
    myNumber = myNumber * myNumber;
}
Try it yourself »

Division by 0 (zero) also generates Infinity:

Example

var x =  2 / 0;          // x will be Infinity
var y = -2 / 0;          // y will be -Infinity
Try it Yourself »

Infinity is a number: typeOf Infinity returns number.

Example

typeof Infinity;        // returns "number"
Try it Yourself »

NaN - Not a Number

NaN is a JavaScript reserved word indicating that a value is not a number.

Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):

Example

var x = 100 / "Apple";  // x will be NaN (Not a Number)
Try it Yourself »

However, if the string contains a numeric value , the result will be a number:

Example

var x = 100 / "10";     // x will be 10
Try it Yourself »

You can use the global JavaScript function isNaN() to find out if a value is a number.

Example

var x = 100 / "Apple";
isNaN(x);               // returns true because x is Not a Number
Try it Yourself »

Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN:

Example

var x = NaN;
var y = 5;
var z = x + y;         // z will be NaN
Try it Yourself »

 Or the result might be a concatenation:

Example

var x = NaN;
var y = "5";
var z = x + y;         // z will be NaN5
Try it Yourself »

NaN is a number, and typeof NaN returns number:

Example

typeof NaN;             // returns "number"
Try it Yourself »

Numbers Can be Objects

Normally JavaScript numbers are primitive values created from literals: var x = 123

But numbers can also be defined as objects with the keyword new: var y = new Number(123)

Example

var x = 123;
var y = new Number(123);

// typeof x returns number
// typeof y returns object
Try it yourself »

Note Don't create Number objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:

When using the == equality operator, equal numbers looks equal:

Example

var x = 500;             
var y = new Number(500);

// (x == y) is true because x and y have equal values
Try it Yourself »

When using the === equality operator, equal numbers are not equal, because the === operator expects equality in both type and value.

Example

var x = 500;             
var y = new Number(500);

// (x === y) is false because x and y have different types
Try it Yourself »

Or even worse. Objects cannot be compared:

Example

var x = new Number(500);             
var y = new Number(500);

// (x == y) is false because objects cannot be compared
Try it Yourself »
Note JavaScript objects cannot be compared.

Number Properties and Methods

Primitive values (like 3.14 or 2014), cannot have properties and methods (because they are not objects).

But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.


Number Properties

Property Description
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
NaN Represents a "Not-a-Number" value
POSITIVE_INFINITY Represents infinity (returned on overflow)

Example

var x = Number.MAX_VALUE;
Try it yourself »

Number properties belongs to the JavaScript's number object wrapper called Number.

These properties can only be accessed as Number.MAX_VALUE.

Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or value, will return undefined:

Example

var x = 6;
var y = x.MAX_VALUE;    // y becomes undefined
Try it yourself »

Note Number methods are covered in the next chapter

 







JavaScript Number Methods


Number methods help you to work with numbers.


Global Methods

JavaScript global functions can be used on all JavaScript data types.

These are the most relevant methods, when working with numbers:

Method Description
Number() Returns a number, converted from its argument.
parseFloat() Parses its argument and returns a floating point number
parseInt() Parses its argument and returns an integer

Number Methods

JavaScript number methods are methods that can be used on numbers:

Method Description
toString() Returns a number as a string
toExponential() Returns a string, with a number rounded and written using exponential notation.
toFixed() Returns a string, with a number rounded and written with a specified number of decimals.
toPrecision() Returns a string, with a number written with a specified length
valueOf() Returns a number as a number

Note All number methods return a new value. They do not change the original variable.


The toString() Method

toString() returns a number as a string.

All number methods can be used on any type of numbers (literals, variables, or expressions):

Example

var x = 123;
x.toString();            // returns 123 from variable x
(123).toString();        // returns 123 from literal 123
(100 + 23).toString();   // returns 123 from expression 100 + 23
Try it Yourself »

The toExponential() Method

toExponential() returns a string, with a number rounded and written using exponential notation.

A parameter defines the number of characters behind the decimal point:

Example

var x = 9.656;
x.toExponential(2);     // returns 9.66e+0
x.toExponential(4);     // returns 9.6560e+0
x.toExponential(6);     // returns 9.656000e+0
Try it yourself »

The parameter is optional. If you don't specify it, JavaScript will not round the number.


The toFixed() Method

toFixed() returns a string, with the number written with a specified number of decimals:

Example

var x = 9.656;
x.toFixed(0);           // returns 10
x.toFixed(2);           // returns 9.66
x.toFixed(4);           // returns 9.6560
x.toFixed(6);           // returns 9.656000
Try it yourself »

Note toFixed(2) is perfect for working with money.


The toPrecision() Method

toPrecision() returns a string, with a number written with a specified length:

Example

var x = 9.656;
x.toPrecision();        // returns 9.656
x.toPrecision(2);       // returns 9.7
x.toPrecision(4);       // returns 9.656
x.toPrecision(6);       // returns 9.65600
Try it Yourself »

Converting Variables to Numbers

There are 3 JavaScript functions that can be used to convert variables to numbers:

These methods are not number methods, but global JavaScript methods.


The Number() Method

Number(), can be used to convert JavaScript variables to numbers:

Example

x = true;
Number(x);        // returns 1
x = false;     
Number(x);        // returns 0
x = new Date();
Number(x);        // returns 1404568027739
x = "10"
Number(x);        // returns 10
x = "10 20"
Number(x);        // returns NaN
Try it Yourself »
Note Used on Date(), the Number() method returns the number of milliseconds since 1.1.1970.

The parseInt() Method

parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:

Example

parseInt("10");         // returns 10
parseInt("10.33");      // returns 10
parseInt("10 20 30");   // returns 10
parseInt("10 years");   // returns 10
parseInt("years 10");   // returns NaN 
Try it yourself »

If the number cannot be converted, NaN (Not a Number) is returned.


The parseFloat() Method

parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned:

Example

parseFloat("10");        // returns 10
parseFloat("10.33");     // returns 10.33
parseFloat("10 20 30");  // returns 10
parseFloat("10 years");  // returns 10
parseFloat("years 10");  // returns NaN
Try it yourself »

If the number cannot be converted, NaN (Not a Number) is returned.


The valueOf() Method

valueOf() returns a number as a number.

Example

var x = 123;
x.valueOf();            // returns 123 from variable x
(123).valueOf();        // returns 123 from literal 123
(100 + 23).valueOf();   // returns 123 from expression 100 + 23
Try it Yourself »

In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object).

The valueOf() method is used internally in JavaScript to convert Number objects to primitive values.

There is no reason to use it in your code.

Note In JavaScript, all data types have a valueOf() and a toString() method.

 







JavaScript Math Object


The Math object allows you to perform mathematical tasks on numbers.


The Math Object

The Math object allows you to perform mathematical tasks.

The Math object includes several mathematical methods.


One common use of the Math object is to create a random number:

Example

Math.random();       // returns a random number
Try it yourself »

Note  Math has no constructor. No methods have to create a Math object first.


Math.min() and Math.max()

Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:

Example

Math.min(0, 150, 30, 20, -8, -200);      // returns -200
Try it yourself »

Example

Math.max(0, 150, 30, 20, -8, -200);      // returns 150
Try it yourself »

Math.random()

Math.random() returns a random number between 0 (inclusive),  and 1 (exclusive):

Example

Math.random();              // returns a random number
Try it Yourself »
Note Math.random() always returns a number lower than 1.

Math.round()

Math.round() rounds a number to the nearest integer:

Example

Math.round(4.7);            // returns 5
Math.round(4.4);             // returns 4
Try it Yourself »

Math.ceil()

Math.ceil() rounds a number up to the nearest integer:

Example

Math.ceil(4.4);             // returns 5
Try it Yourself »

Math.floor()

Math.floor() rounds a number down to the nearest integer:

Example

Math.floor(4.7);            // returns 4
Try it Yourself »

Math.floor() and Math.random() can be used together to return a random number between 0 and 10:

Example

Math.floor(Math.random() * 11);   // returns a random number between 0 and 10
Try it Yourself »

Math Constants

JavaScript provides 8 mathematical constants that can be accessed with the Math object:

Example

Math.E          // returns Euler's number
Math.PI         // returns PI
Math.SQRT2      // returns the square root of 2
Math.SQRT1_2    // returns the square root of 1/2
Math.LN2        // returns the natural logarithm of 2
Math.LN10       // returns the natural logarithm of 10
Math.LOG2E      // returns base 2 logarithm of E
Math.LOG10E     // returns base 10 logarithm of E
Try it yourself »

Math Object Methods

Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle

 







JavaScript Dates


The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and milliseconds)


JavaScript Date Formats

A JavaScript date can be written as a string:

or as a number:

Dates written as numbers, specifies the number of milliseconds since January 1, 1970, 00:00:00.


Displaying Dates

In this tutorial we use a script to display dates inside a <p> element with id="demo":

Example

< p id="demo"></p>

< script>
document.getElementById("demo").innerHTML = Date();
< /script>
Try it Yourself »

The script above says: assign the value of Date() to the content (innerHTML) of the element with id="demo". 

Note You will learn how to display a date, in a more readable format, at the bottom of this page.

Creating Date Objects

The Date object lets us work with dates.

A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.

Date objects are created with the new Date() constructor.

There are 4 ways of initiating a date:

new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

Using new Date(), creates a new date object with the current date and time:

Example

< script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
< /script>
Try it Yourself »

Using new Date(date string), creates a new date object from the specified date and time:

Example

< script>
var d = new Date("October 13, 2014 11:13:00");
document.getElementById("demo").innerHTML = d;
< /script>
Try it Yourself »
Note Valid date strings (date formats) are described in the next chapter.

Using new Date(number), creates a new date object as zero time plus the number.

Zero time is 01 January 1970 00:00:00 UTC. The number is specified in milliseconds:

Example

< script>
var d = new Date(86400000);
document.getElementById("demo").innerHTML = d;
< /script>
Try it Yourself »

Note JavaScript dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC). One day contains 86,400,000 millisecond.

Using new Date(7 numbers), creates a new date object with the specified date and time:

The 7 numbers specify the year, month, day, hour, minute, second, and millisecond, in that order:

Example

< script>
var d = new Date(99,5,24,11,33,30,0);
document.getElementById("demo").innerHTML = d;
< /script>
Try it Yourself »

Variants of the example above let us omit any of the last 4 parameters:

Example

< script>
var d = new Date(99,5,24);
document.getElementById("demo").innerHTML = d;
< /script>
Try it Yourself »

Note JavaScript counts months from 0 to 11. January is 0. December is 11.


Date Methods

When a Date object is created, a number of methods allow you to operate on it.

Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of objects, using either local time or UTC (universal, or GMT) time.

Note Date methods are covered in a later chapter.


Displaying Dates

When you display a date object in HTML, it is automatically converted to a string, with the toString() method.

Example

< p id="demo"></p>

< script>
d = new Date();
document.getElementById("demo").innerHTML = d;
< /script>

Is the same as:

< p id="demo"></p>

< script>
d = new Date();
document.getElementById("demo").innerHTML = d.toString();
< /script>
Try it Yourself »

The toUTCString() method converts a date to a UTC string (a date display standard).

Example

< script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toUTCString();
</script>
Try it Yourself »

The toDateString() method converts a date to a more readable format:

Example

< script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toDateString();
</script>
Try it Yourself »
Note Date objects are static, not dynamic. The computer time is ticking, but date objects, once created, are not.

Time Zones

When setting a date, without specifying the time zone, JavaScript will use the browser's time zone.

When getting a date, without specifying the time zone, the result is converted to the browser's time zone.

In other words: If a date/time is created in GMT (Greenwich Mean Time), the date/time will be converted to CDT (Central US Daylight Time) if a user browses from central US.

Note Read more about time zones in the next chapters.