Comp 110 Built-In Math Functions

Built-In Math Functions

There is a special 'built-in class' called Math with useful functions defined in it. We call these functions using the syntax:

Math.<function name>(<parameter>);

Below are some of the functions included in this class:

  • Math.floor(n: number): number          rounds a number down
  • Math.round(n: number): number        rounds a number >= 0.5 up, < 0.5 down
  • Math.ceil (roof: number): number      rounds a number up
  • Math.random(): number                     generates a random decimal >= 0.0 and < 1.0
  • Math.abs(n: number): number            absolute value of a number
  • Math.sqrt(n: number): number           square root

Additional functions (including trigonometric functions) can be found here.

Examples of function use:

let squareOfTwo = Math.sqrt(2);
print(squareOfTwo); //4 is printed

let randomDecimal = Math.random();
print(randomDecimal); //a random number <= 1 and >=0 is printed

print(Math.round(.96)); //1 is printed