Inflation is the rate at which the general level of prices for goods and services is rising, and subsequently, purchasing power is falling. Inflation can be calculated by comparing the Consumer Price Index (CPI) from one period to another. The formula to calculate the inflation rate is:
Inflation Rate = [(CPI in Current Period – CPI in Previous Period) / CPI in Previous Period] * 100
Where:
CPI in Current Period: The Consumer Price Index for the more recent time frame.
CPI in Previous Period: The Consumer Price Index for the earlier time frame.
function calculateInflation() {
var currentCPI = parseFloat(document.getElementById("current_cpi").value);
var previousCPI = document.getElementById("previous_cpi").value;
// Validate inputs
if (isNaN(currentCPI) || isNaN(previousCPI) || previousCPI == 0) {
document.getElementById("result").innerHTML = "Please enter valid numbers for both CPI values, and ensure the Previous CPI is not zero.";
return;
}
previousCPI = parseFloat(previousCPI); // Ensure previousCPI is also a float
var inflationRate = ((currentCPI – previousCPI) / previousCPI) * 100;
// Display the result
document.getElementById("result").innerHTML =
"The calculated inflation rate is: " + inflationRate.toFixed(2) + "%";
}
#inflation-calculator {
font-family: sans-serif;
border: 1px solid #ccc;
padding: 20px;
border-radius: 8px;
max-width: 500px;
margin: 20px auto;
background-color: #f9f9f9;
}
#inflation-calculator h2 {
text-align: center;
color: #333;
margin-bottom: 20px;
}
.input-section {
margin-bottom: 15px;
}
.input-section label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #555;
}
.input-section input[type="number"] {
width: calc(100% – 12px);
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box; /* Include padding and border in the element's total width and height */
}
#inflation-calculator button {
display: block;
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease;
}
#inflation-calculator button:hover {
background-color: #45a049;
}
#result {
margin-top: 20px;
padding: 10px;
background-color: #e0f0e0;
border: 1px solid #c0dcc0;
border-radius: 4px;
text-align: center;
font-size: 1.1em;
}