- Computing the total cost of an order – If you have the quantity of a product and its price, you can multiply these two numbers to get the total cost of the order.
- Scaling images or dimensions – If you want to resize an image or scale a set of dimensions, you can use multiplication.
- Calculating percentages – Percentages are often used in finance and business. You can use multiplication to calculate percentages, such as the percentage of a discount or the percentage of a tax.
- Performing mathematical calculations – Multiplication is a key operation in many mathematical calculations, such as finding the area of a rectangle, the volume of a cylinder, or the rate of change of a function.
You can multiply two numbers using the following methods:
(*) operator as shown.
let a = 5; let b = 10; let product = a * b; console.log(product);
In this example, we create two variables, a and b, assign them the values 5 and 10, respectively, and multiply them using the
* operator. The result is stored in a third variable product, then printed to the console.
The following example begins by defining two variables (num1 and num2) and assigning them the values of 10 and 5, respectively.
We then use the
"*" operator to multiply num1 by num2 and store the result in a product variable. Finally, we log the product’s value to the console, which should output 50.
const num1 = 10; const num2 = 5; const product = num1 * num2; console.log(product);
Number() function as shown.
const num1 = "10"; const num2 = "5"; const product = Number(num1) * Number(num2); console.log(product);
This method multiplies two numbers by first converting the strings into numbers before using the
“*” operator to multiply the numbers.
parseFloat() function as shown below.
const num1 = "10"; const num2 = "5"; const product = parseFloat(num1) * parseFloat(num2); console.log(product);
This method also works by first converting the strings into numbers before multiplying them with each other.
multiply() method that can be used to multiply two numbers.
let a = 5; let b = 10; let product = Math.multiply(a, b); console.log(product);
In this example, we use the
multiply() method of the Math object to multiply the variables a and b. The result is stored in the product variable, then printed to the console.
Note that the
These methods achieve the same result of multiplying two numbers together, but they have different use cases depending on the situation.
For example, using variables and the
"*" operator is the simplest and most straightforward method while using
parseFloat() functions are useful when working with user input or when the numbers are stored as strings.