如何使用HTML、CSS和JavaScript建立損益計算器?


在這篇文章中,我們將使用JavaScript建立一個計算器。我們將使用基本的數學公式來計算損益。我們將以百分比和實際值的形式返回結果。

為了計算損益,我們需要兩樣東西:**成本價 (CP)** 和 **售價 (SP)**。

計算損益的公式:

  • 利潤:SP – CP

  • 利潤百分比:利潤/CP * 100

  • 虧損:SP – CP

  • 虧損百分比:虧損/CP * 100

示例 1

在下面的示例中,我們建立了一個計算器,它將根據成本價和售價計算損益百分比。

點選“計算”按鈕,它將呼叫一個函式,該函式將獲取 CP 和 SP 輸入,然後計算損益。

#檔名: index.html

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

輸出

成功執行上述程式後,它將生成一個損益計算器。您可以輸入成本價和售價。輸入成本價和售價後,您可以點選“計算損益”按鈕來計算利潤或虧損。

更新於:2022年4月21日

2K+ 次檢視

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.