Calculate the Profit Margin and the Gross Profit Rate
function calculateProfit() {
var revenueInput = document.getElementById("revenue");
var cogsInput = document.getElementById("cogs");
var resultDiv = document.getElementById("result");
var revenue = parseFloat(revenueInput.value);
var cogs = parseFloat(cogsInput.value);
if (isNaN(revenue) || isNaN(cogs)) {
resultDiv.innerHTML = "Please enter valid numbers for both Revenue and COGS.";
return;
}
if (revenue < 0 || cogs 0) {
grossProfitMargin = (grossProfit / revenue) * 100;
} else if (grossProfit < 0) {
// Handle case where revenue is 0 but cogs is positive (loss)
grossProfitMargin = -Infinity; // Or a large negative number to indicate significant loss
} else {
// Revenue is 0, COGS is 0 or positive. If COGS is 0, profit is 0, margin is 0.
// If COGS is positive, it's a loss, handled above.
grossProfitMargin = 0;
}
resultDiv.innerHTML =
"Gross Profit: " + grossProfit.toFixed(2) + "" +
"Gross Profit Margin: " + grossProfitMargin.toFixed(2) + "%";
}
.calculator-widget {
font-family: Arial, sans-serif;
border: 1px solid #ccc;
padding: 20px;
border-radius: 8px;
max-width: 600px;
margin: 20px auto;
background-color: #f9f9f9;
}
.calculator-widget h2 {
text-align: center;
color: #333;
margin-bottom: 20px;
}
.calculator-inputs {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 15px;
margin-bottom: 20px;
align-items: end;
}
.calculator-inputs .input-group {
display: flex;
flex-direction: column;
}
.calculator-inputs label {
font-weight: bold;
margin-bottom: 5px;
color: #555;
}
.calculator-inputs input[type="number"] {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
}
.calculator-inputs button {
grid-column: 1 / -1; /* Span across both columns */
padding: 12px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.calculator-inputs button:hover {
background-color: #0056b3;
}
.calculator-results {
margin-top: 20px;
padding: 15px;
background-color: #e9ecef;
border-radius: 4px;
}
.calculator-results h3 {
margin-top: 0;
color: #333;
}
.calculator-results p {
margin: 5px 0;
font-size: 1.1em;
}
.calculator-results strong {
color: #007bff;
}
.calculator-explanation {
margin-top: 30px;
border-top: 1px solid #eee;
padding-top: 20px;
color: #444;
line-height: 1.6;
}
.calculator-explanation h4 {
margin-top: 15px;
color: #333;
}
.calculator-explanation p, .calculator-explanation ul {
margin-bottom: 15px;
}
.calculator-explanation ul li {
margin-bottom: 8px;
}