JavaScript Number Methods and Math Methods

JavaScript provides built-in methods and properties for working with numbers. You can round decimal values, control the number of digits displayed, generate random numbers, find the largest or smallest value, and perform mathematical calculations.

These features are useful when building calculators, shopping applications, games, financial tools, and other JavaScript projects.

In this tutorial, you will learn nine important number and math methods: toFixed(), toPrecision(), Math.round(), Math.floor(), Math.ceil(), Math.random(), Math.max(), Math.min(), and Math.pow().

What Are JavaScript Number Methods?

JavaScript number methods help you format numeric values or perform calculations. Some methods belong to number values, while others belong to the built-in Math object.

For example, toFixed() formats a number with a specified number of digits after the decimal point.

const price = 125.678;

console.log(price.toFixed(2));

Output:

125.68

The toFixed() method returns a string, not a number. In contrast, methods such as Math.round() return numeric values.

If you are new to JavaScript data types, review JavaScript data types before continuing.

toFixed() Method in JavaScript

The toFixed() method formats a number using a specified number of digits after the decimal point.

Syntax:

number.toFixed(digits);

The digits argument is optional and can range from 0 to 100. If omitted, it defaults to 0.

Example of toFixed()

const price = 45.6789;

console.log(price.toFixed(0));
console.log(price.toFixed(2));
console.log(price.toFixed(3));

Output:

46
45.68
45.679

The method rounds the displayed value as needed and pads with zeros when necessary.

Using toFixed() for Prices

const price = 199.5;

console.log(price.toFixed(2));

Output:

199.50

This is useful when displaying prices with two decimal places.

Remember that toFixed() returns a string.

const price = 199.5;

const formattedPrice = price.toFixed(2);

console.log(formattedPrice);
console.log(typeof formattedPrice);

Output:

199.50
string

If you need a numeric result for further calculations, convert the formatted string using Number().

const price = 199.5;

const formattedPrice = Number(price.toFixed(2));

console.log(formattedPrice);
console.log(typeof formattedPrice);

Output:

199.5
number

For financial applications, remember that formatting a number to two decimal places does not eliminate floating-point precision issues in calculations.

toPrecision() Method in JavaScript

The toPrecision() method formats a number to a specified number of significant digits.

Significant digits include the meaningful digits of a number, starting from its first nonzero digit. Unlike toFixed(), which controls digits after the decimal point, toPrecision() controls the total number of significant digits.

Syntax:

number.toPrecision(precision);

The precision argument is optional and, when supplied, must be between 1 and 100.

Example of toPrecision()

const number = 123.456;

console.log(number.toPrecision(3));
console.log(number.toPrecision(5));
console.log(number.toPrecision(7));

Output:

123
123.46
123.4560

The method rounds the value to the requested number of significant digits. It may add zeros or use scientific notation when appropriate.

Difference Between toFixed() and toPrecision()

const number = 123.456;

console.log(number.toFixed(2));
console.log(number.toPrecision(5));

Output:

123.46
123.46

Although the outputs look the same here, the methods use different rules.

MethodWhat it controlsExample
toFixed(2)Digits after the decimal point123.46
toPrecision(5)Total significant digits123.46

Consider a smaller number:

const number = 0.004567;

console.log(number.toFixed(3));
console.log(number.toPrecision(3));

Output:

0.005
0.00457

The first method keeps three decimal places. The second keeps three significant digits.

Math.round() Method in JavaScript

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

Syntax:

Math.round(number);

Example of Math.round()

console.log(Math.round(4.3));
console.log(Math.round(4.7));
console.log(Math.round(8.5));

Output:

4
5
9

For positive numbers, decimal parts below 0.5 round down, while decimal parts of 0.5 or greater round up.

Negative numbers have a specific rule: ties at exactly halfway round toward positive infinity.

console.log(Math.round(-4.3));
console.log(Math.round(-4.5));
console.log(Math.round(-4.7));

Output:

-4
-4
-5

Use Math.round() when you need a number rounded to the nearest integer.

Math.floor() Method in JavaScript

The Math.floor() method rounds a number down to the greatest integer less than or equal to that number.

Syntax:

Math.floor(number);

Example of Math.floor()

console.log(Math.floor(4.9));
console.log(Math.floor(4.2));
console.log(Math.floor(7.0));

Output:

4
4
7

Math.floor() always moves toward negative infinity, which matters when working with negative numbers.

console.log(Math.floor(-4.2));
console.log(Math.floor(-4.9));

Output:

-5
-5

Even though -4.2 is closer to -4, flooring it produces -5.

Math.ceil() Method in JavaScript

The Math.ceil() method rounds a number up to the smallest integer greater than or equal to that number.

Syntax:

Math.ceil(number);

Example of Math.ceil()

console.log(Math.ceil(4.1));
console.log(Math.ceil(4.8));
console.log(Math.ceil(7.0));

Output:

5
5
7

The method moves toward positive infinity.

console.log(Math.ceil(-4.2));
console.log(Math.ceil(-4.9));

Output:

-4
-4

Difference Between Math.round(), Math.floor(), and Math.ceil()

MethodBehaviorExample with 4.7Result
Math.round()Nearest integerMath.round(4.7)5
Math.floor()Down toward negative infinityMath.floor(4.7)4
Math.ceil()Up toward positive infinityMath.ceil(4.7)5

These methods are useful for calculations involving quantities, pagination, prices, and game scores. Choose the method according to the rounding rule your application requires.

Math.random() Method in JavaScript

The Math.random() method generates a pseudo-random number greater than or equal to 0 and less than 1.

Syntax:

Math.random();

Example of Math.random()

console.log(Math.random());
console.log(Math.random());
console.log(Math.random());

Example output:

0.273451...
0.817263...
0.094526...

Your actual results will vary each time the code runs.

Generating a Random Integer

You can combine Math.random() with Math.floor() to generate a random integer between 0 and 9.

const randomNumber = Math.floor(Math.random() * 10);

console.log(randomNumber);

Example output:

7

The result can be any integer from 0 through 9.

Generating a Random Number Within a Range

To generate a random integer between a minimum and maximum value, including both endpoints, use this formula:

Math.floor(Math.random() * (max - min + 1)) + min;

For example, generate a number between 1 and 6, like a dice roll.

const dice = Math.floor(Math.random() * 6) + 1;

console.log(dice);

Example output:

4

The output can be any integer from 1 to 6.

Math.random() is suitable for simple games and demonstrations, but it is not cryptographically secure. For security-sensitive random values, use crypto.getRandomValues() instead.

Math.max() Method in JavaScript

The Math.max() method returns the largest of the numbers supplied as arguments.

Syntax:

Math.max(number1, number2, number3);

Example of Math.max()

console.log(Math.max(10, 25, 5, 40, 15));

Output:

40

The largest number is 40.

Using Math.max() With an Array

Math.max() accepts separate arguments, not an array directly. You can use the spread operator (...) to pass an array’s elements as individual arguments.

const numbers = [10, 25, 5, 40, 15];

console.log(Math.max(...numbers));

Output:

40

For an empty array, Math.max(...[]) returns -Infinity. For a large array, avoid spreading an extremely large number of elements into a function call because argument limits may be exceeded.

Math.min() Method in JavaScript

The Math.min() method returns the smallest of the numbers supplied as arguments.

Syntax:

Math.min(number1, number2, number3);

Example of Math.min()

console.log(Math.min(10, 25, 5, 40, 15));

Output:

5

The smallest number is 5.

Using Math.min() With an Array

You can use the spread operator to pass an array’s elements to Math.min().

const prices = [499, 299, 799, 199, 599];

console.log(Math.min(...prices));

Output:

199

This technique is useful when finding the lowest price, minimum score, or smallest measurement in a collection.

Difference Between Math.max() and Math.min()

MethodPurposeExampleResult
Math.max()Finds the largest numberMath.max(5, 10, 3)10
Math.min()Finds the smallest numberMath.min(5, 10, 3)3

Both methods return -Infinity and Infinity, respectively, when called without arguments.

Math.pow() Method in JavaScript

The Math.pow() method raises a base number to the power of an exponent.

Syntax:

Math.pow(base, exponent);

Example of Math.pow()

console.log(Math.pow(2, 3));
console.log(Math.pow(5, 2));
console.log(Math.pow(10, 3));

Output:

8
25
1000

These calculations represent:

  • (2^3 = 2 \times 2 \times 2 = 8)
  • (5^2 = 5 \times 5 = 25)
  • (10^3 = 10 \times 10 \times 10 = 1000)

Using the Exponentiation Operator

JavaScript also supports the exponentiation operator (**), which often provides a shorter alternative to Math.pow().

console.log(2 ** 3);
console.log(5 ** 2);
console.log(10 ** 3);

Output:

8
25
1000

Both approaches work for many common exponent calculations.

Practical Example Using JavaScript Number and Math Methods

The following example combines several methods to calculate and format a product’s price and generate a simple random discount percentage.

const product = {
    name: "Wireless Mouse",
    price: 799.456
};

// Format the price to two decimal places
const formattedPrice = product.price.toFixed(2);

// Generate a random discount from 5% to 15%
const discount = Math.floor(Math.random() * 11) + 5;

// Calculate the discounted price
const discountedPrice = product.price * (1 - discount / 100);

console.log("Product:", product.name);
console.log("Original price: ₹" + formattedPrice);
console.log("Discount:", discount + "%");
console.log("Discounted price: ₹" + discountedPrice.toFixed(2));

Example output:

Product: Wireless Mouse
Original price: ₹799.46
Discount: 10%
Discounted price: ₹719.51

The discount and discounted price may differ each time the program runs because the discount is generated randomly.

This example demonstrates how number formatting, random number generation, and arithmetic operations can be combined in a practical application. For actual financial calculations, consider using integer minor units, such as paise, or a decimal arithmetic library to avoid floating-point precision issues.

Frequently Asked Questions

What is the difference between toFixed() and toPrecision()?

toFixed() controls the number of digits after the decimal point, while toPrecision() controls the total number of significant digits. Both return strings.

What is the difference between Math.round(), Math.floor(), and Math.ceil()?

Math.round() rounds to the nearest integer, Math.floor() rounds toward negative infinity, and Math.ceil() rounds toward positive infinity.

How do you generate a random integer in JavaScript?

Use Math.floor(Math.random() * range) + minimum to generate an integer in a range. For a range from 1 to 6, use Math.floor(Math.random() * 6) + 1.

What does Math.max() return?

It returns the largest number among the supplied arguments. Use Math.max(...numbers) to find the largest value in an array.

What does Math.min() return?

It returns the smallest number among the supplied arguments. Use Math.min(...numbers) to find the smallest value in an array.

What is the difference between Math.pow() and the ** operator?

Both calculate exponentiation. For example, Math.pow(2, 3) and 2 ** 3 both return 8.

Does toFixed() return a number?

No. toFixed() returns a string. If you need a number, you can convert the result using Number().

What to Learn Next

After learning JavaScript number and math methods, continue with JavaScript Type Conversion to understand how to convert strings, numbers, and other values between different data types.

1 thought on “JavaScript Number Methods and Math Methods”

Comments are closed.