JavaScript/Numbers

From Wikibooks, open books for an open world
Jump to: navigation, search
Previous: Variables and Types Index Next: Strings

JavaScript implement numbers as floating point values, that is, they're attaining decimal values as well as whole number values.

Basic Use[edit]

To make a new 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)

Number literals define the number value. 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. (8 and 9 are not octal digits, and if found, cause the integer to be read in the normal base-10).
  • An integer literal may also be found with prefixed "0x", to indicate a hexadecimal number.

The Math Object[edit]

Unlike strings, arrays, and dates, the numbers aren't objects, so they don't contain any methods that can be accessed by the normal dot notation. Instead a certain Math object provides usual numeric functions and constants as methods and properties. The methods and properties of the Math object are referenced using the dot operator in the usual way, for example:

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

Methods[edit]

random()[edit]

Generates a pseudo-random number.

var myInt = Math.random();

max(int1, int2)[edit]

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

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

min(int1, int2)[edit]

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

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

floor(float)[edit]

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

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

ceil(float)[edit]

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

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

round(float)[edit]

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

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

Properties[edit]

Properties of the Math Object are most 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.

Further reading[edit]


Previous: Variables and Types Index Next: Strings