Math in JavaScript

Math In JavaScript - basic

Overview

is a built-in object that has properties and methods for mathematical constants and functions. It’s not a function object. Some of Useful common method of math are abs(), ceil(), floor(), min(), max(), random(), round(), sqrt().

Let’s a discus about them.

abs()

abs() is the method that returns the absolute value of a number. That means it return a positive value though calculated result is negative.

example:

const a=10, b=20;

console.log(Math.abs(a-b)) // output: 10 (return absolute value of result)

ceil()

This method is use to return a integer number from float number. ceil() method always rounds a number up to the next largest integer.

example:

console.log(Math.ceil(3.2)) // output: 4

floor()

This method returns the largest integer less than or equal to a given number.

example:

console.log(Math.floor(3.7)) // output: 3

round()

This method returns the value of a number rounded to the nearest integer.

example:

console.log(Math.round(3.4)) // output: 3

console.log(Math.round(3.5)) // output: 4

random()

This method return random float number from 0 to 1. You can control the range of random number.

example:

console.log(Math.random())// output : from 0 to 1 random number (float)

console.log(Math.random() * 1000)// output : from 0 to 1000 random number(float)

console.log(Math.floor(Math.random() * 1000))// output : from 0 to 1000 random number (integer)

sqrt()

This method function returns the square root of a number.

example:

console.log(Math.sqrt(4)) // output: 2

max()

This method return the maximum number that give you as parameter.

example:

console.log(Math.max(1, 2, 6, 4, 8, 3)) // output: 8

min()

This method return the minimum number that give you as parameter.

example:

console.log(Math.min(1, 2, 6, 4, 8, 3)) // output: 1

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store