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

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

To calculate profit and loss, we need two values: CP (Cost Price) and SP (Selling Price).

Formulas to Calculate Profit and Loss

  • Profit: SP ? CP

  • Profit Percentage: (Profit/CP) × 100

  • Loss: CP ? SP

  • Loss Percentage: (Loss/CP) × 100

Creating the Calculator

The calculator consists of an HTML interface with input fields for cost price and selling price, styled with CSS for better appearance, and JavaScript logic to perform calculations.

Complete Implementation

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Profit and Loss Calculator</title>
   <style>
      body {
         font-family: Arial, sans-serif;
         background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
         margin: 0;
         padding: 20px;
         min-height: 100vh;
         display: flex;
         justify-content: center;
         align-items: center;
      }
      .calculator {
         background: white;
         padding: 30px;
         border-radius: 15px;
         box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
         text-align: center;
         max-width: 400px;
         width: 100%;
      }
      .calculator h1 {
         color: #4CAF50;
         margin-bottom: 10px;
         font-size: 24px;
      }
      .calculator h3 {
         color: #333;
         margin-bottom: 30px;
         font-size: 20px;
      }
      .input-group {
         margin: 20px 0;
         text-align: left;
      }
      .input-group label {
         display: block;
         margin-bottom: 8px;
         color: #555;
         font-weight: bold;
      }
      .input-group input {
         width: 100%;
         padding: 12px;
         border: 2px solid #ddd;
         border-radius: 8px;
         font-size: 16px;
         transition: border-color 0.3s;
         box-sizing: border-box;
      }
      .input-group input:focus {
         outline: none;
         border-color: #4CAF50;
      }
      .calculate-btn {
         background: #4CAF50;
         color: white;
         padding: 12px 30px;
         border: none;
         border-radius: 8px;
         font-size: 16px;
         cursor: pointer;
         margin: 20px 0;
         transition: background 0.3s;
      }
      .calculate-btn:hover {
         background: #45a049;
      }
      .result {
         margin-top: 20px;
         padding: 15px;
         border-radius: 8px;
         font-weight: bold;
      }
      .profit {
         background: #d4edda;
         color: #155724;
         border: 1px solid #c3e6cb;
      }
      .loss {
         background: #f8d7da;
         color: #721c24;
         border: 1px solid #f5c6cb;
      }
      .neutral {
         background: #e2e3e5;
         color: #383d41;
         border: 1px solid #d6d8db;
      }
   </style>
</head>
<body>
   <div class="calculator">
      <h1>Welcome To Tutorials Point</h1>
      <h3>Profit and Loss Calculator</h3>
      
      <div class="input-group">
         <label for="costPrice">Cost Price (CP):</label>
         <input type="number" id="costPrice" placeholder="Enter cost price" min="0" step="0.01">
      </div>
      
      <div class="input-group">
         <label for="sellingPrice">Selling Price (SP):</label>
         <input type="number" id="sellingPrice" placeholder="Enter selling price" min="0" step="0.01">
      </div>
      
      <button class="calculate-btn" onclick="calculateProfitLoss()">Calculate Profit/Loss</button>
      
      <div id="result"></div>
   </div>

   <script>
      function calculateProfitLoss() {
         // Get input values
         const costPrice = parseFloat(document.getElementById('costPrice').value);
         const sellingPrice = parseFloat(document.getElementById('sellingPrice').value);
         const resultDiv = document.getElementById('result');
         
         // Validation
         if (isNaN(costPrice) || isNaN(sellingPrice)) {
            resultDiv.innerHTML = '<div class="result neutral">Please enter valid numbers for both prices</div>';
            return;
         }
         
         if (costPrice <= 0 || sellingPrice < 0) {
            resultDiv.innerHTML = '<div class="result neutral">Please enter positive values</div>';
            return;
         }
         
         // Calculate difference
         const difference = sellingPrice - costPrice;
         
         let resultHTML = '';
         
         if (difference > 0) {
            // Profit case
            const profitPercentage = ((difference / costPrice) * 100).toFixed(2);
            resultHTML = `
               <div class="result profit">
                  <h4>? PROFIT</h4>
                  <p>Amount: ?${difference.toFixed(2)}</p>
                  <p>Percentage: ${profitPercentage}%</p>
               </div>
            `;
         } else if (difference < 0) {
            // Loss case
            const loss = Math.abs(difference);
            const lossPercentage = ((loss / costPrice) * 100).toFixed(2);
            resultHTML = `
               <div class="result loss">
                  <h4>? LOSS</h4>
                  <p>Amount: ?${loss.toFixed(2)}</p>
                  <p>Percentage: ${lossPercentage}%</p>
               </div>
            `;
         } else {
            // No profit, no loss
            resultHTML = `
               <div class="result neutral">
                  <h4>?? BREAK-EVEN</h4>
                  <p>No Profit, No Loss</p>
               </div>
            `;
         }
         
         resultDiv.innerHTML = resultHTML;
      }
      
      // Allow Enter key to calculate
      document.addEventListener('keypress', function(event) {
         if (event.key === 'Enter') {
            calculateProfitLoss();
         }
      });
   </script>
</body>
</html>

How It Works

The calculator performs the following steps:

  1. Input Validation: Checks if entered values are valid numbers and positive
  2. Calculation: Computes the difference between selling price and cost price
  3. Result Display: Shows profit, loss, or break-even status with appropriate styling
  4. Percentage Calculation: Uses the formulas mentioned above to calculate percentages

Key Features

  • Responsive Design: Works on desktop and mobile devices

  • Input Validation: Prevents errors from invalid inputs

  • Visual Feedback: Color-coded results (green for profit, red for loss)

  • Keyboard Support: Press Enter to calculate

  • Decimal Support: Handles fractional currency values

Output

The calculator displays a clean, professional interface where users can enter cost price and selling price. After clicking "Calculate Profit/Loss" or pressing Enter, the result appears with color-coded styling showing the profit or loss amount and percentage.

Conclusion

This profit and loss calculator demonstrates practical application of JavaScript for financial calculations, combining HTML structure, CSS styling, and JavaScript logic to create a functional tool for business analysis.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements