JavaScript/Numbers

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search
Previous: Variables and Types Index Next: Strings

A number is a type of variable which stores an integer.

Contents

[edit] Basic Use

To make a new integer/number, a simple initialization suffices:

var foo = 0; // or whatever number you want

After you have made your number, you can then modify it as necessary. Numbers can be modified or assigned using the operators defined within JavaScript.

foo = 1; //foo = 1
foo += 2; //foo = 3 (the two gets added on)
foo -= 2; //foo = 1 (the two gets removed)

A number literal (which is not linked to a variable) can be used to manipulate these variables by a specific amount. In particular:

  • They appear as a set of digits of varying length.
  • Negative literal numbers have a minus sign before the set of digits.
  • Floating point literal numbers contain one decimal point, and may optionally use the E notation with the character e.
  • An integer literal may be prepended with "0", to indicate that a number is in base-8. (9 is not an octal digit, and if found, causes the integer to be read in the normal base-10.)
  • An integer literal may also be found with "0x", to indicate a hexadecimal number.

[edit] The Math Object

Unlike strings, arrays and dates the integer does not have any objects. However, the Math object may be used. It is an object often used when dealing with numbers. These methods and properties help in the calculation of more complex calculations. The methods and properties of the Math object are referenced using the "dot" operator:

var varOne = Math.ceil(8.5);
var varPi = Math.PI;

[edit] Methods

[edit] random()

Generates a psuedo-random number.

var myInt = Math.random();

[edit] max(int1, int2)

Returns the highest number from the two numbers passed as arguments.

var myInt = Math.max(8, 9);
document.write(myInt); //9

[edit] min(int1, int2)

Returns the lowest number from the two numbers passed as arguments.

var myInt = Math.min(8, 9);
document.write(myInt); //8

[edit] floor(float)

Returns the greatest integer less than the number passed as an argument.

var myInt = Math.floor(90.8);
document.write(myInt); //90;

[edit] ceil(float)

Returns the least integer greater than the number passed as an argument.

var myInt = Math.ceil(90.8);
document.write(myInt); //91;

[edit] round(float)

Returns the closest integer to the number passed as an argument.

var myInt = Math.round(90.8);
document.write(myInt); //91;

[edit] Properties

Properties of the Math Object are mostly commonly used constants.

  • PI: Returns the value of pi.
  • E: Returns the constant e.
  • SQRT2: Returns the square root of 2.
  • LN10: Returns the natural logarithm of 10.
  • LN2: Returns the natural logarithm of 2.

[edit] Further reading


Previous: Variables and Types Index Next: Strings
In other languages