How to Create a Profit and Loss Calculator using HTML, CSS, and JavaScript?

JavascriptWeb DevelopmentFront End Technology

In this article, we are going to create a calculator using JavaScript We will be using the basic math formulas to calculate the profit and loss. We will be returning the result in percentage along with the actual values.

To calculate the Profit and Loss we need two things that are: CP (Cost Price) and SP (Selling Price).

Formulas to Calculate Profit and Loss −

  • Profit: SP – CP

  • Profit Percentage: Profit/CP * 100

  • Loss: SP – CP

  • Loss Percentage: Loss/CP * 100

Example 1

In the example below, we have created a calculator that will calculate the profit and loss percentage as per the cost price and the selling price.

On clicking the Calculate button, it will call the function that will get the CP & SP inputs and then calculate the profit and loss.

#Filename: index.html

<!DOCTYPE html>
<html lang="en">
   <title>Profit and Loss Calculator</title>
   <div class="plcalculate">
      <h1 style="color: green;">
         Welcome To Tutorials Point
      <h3>Profit and Loss Calculator</h3>
      <p>Enter the Cost Price(CP) :
         <input class="cp" type="number" />
      <p>Enter the Selling Price(SP) :
         <input class="sp" type="number" />
      <button onclick="Calculate()">Calculate Profit/Loss</button>
         <h2 class="loss"></h2>
         <h2 class="lossPercentage"></h2>
         <h2 class="nothing"></h2>
      function Calculate(){
         const CP= document.querySelector(".cp").value;
         const SP= document.querySelector(".sp").value;
         const profitLoss=document.querySelector(".loss");
         const percentage=document.querySelector(".lossPercentage");
         const nothing=document.querySelector(".nothing");
         const diff=SP - CP;
            const profit_percent= ((diff/CP)*100).toFixed(2);
            profitLoss.innerHTML="It is a Profit of: INR "+ diff;
            percentage.innerHTML="Total Profit Percentage : "+
         } else if(diff<0){
            const loss_percent= ((Math.abs(diff)/CP)*100).toFixed(2);
            profitLoss.innerHTML="It is a Loss of: INR "+ Math.abs(diff);
            percentage.innerHTML="Total Loss Percentage : "+ loss_percent;
         } else if(diff==0){
            nothing.innerHTML="No Profit No Loss";


On successful execution of the above program, it will produce a Profit and Loss calculator. You can enter Cost Price and Selling Price. After entering the Cost Price and Selling Price, you can calculate the profit or loss by clicking the button “Calculate Profit/Loss”.

Updated on 21-Apr-2022 12:16:56