How to Calculate Discounted Cash Flow

Discounted Cash Flow (DCF) Calculator & Guide :root { –primary-color: #004a99; –success-color: #28a745; –background-color: #f8f9fa; –text-color: #333; –border-color: #ddd; –card-background: #fff; –shadow: 0 2px 5px rgba(0,0,0,0.1); } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: var(–background-color); color: var(–text-color); line-height: 1.6; margin: 0; padding: 0; } .container { max-width: 1000px; margin: 20px auto; padding: 20px; background-color: var(–card-background); border-radius: 8px; box-shadow: var(–shadow); } header { text-align: center; margin-bottom: 30px; padding-bottom: 20px; border-bottom: 1px solid var(–border-color); } header h1 { color: var(–primary-color); margin-bottom: 10px; } .calculator-section { margin-bottom: 40px; padding: 25px; border: 1px solid var(–border-color); border-radius: 8px; background-color: var(–card-background); box-shadow: var(–shadow); } .calculator-section h2 { color: var(–primary-color); margin-top: 0; margin-bottom: 20px; text-align: center; } .input-group { margin-bottom: 15px; display: flex; flex-direction: column; align-items: flex-start; } .input-group label { display: block; margin-bottom: 8px; font-weight: bold; color: var(–primary-color); } .input-group input[type="number"], .input-group input[type="text"], .input-group select { width: calc(100% – 20px); padding: 10px; border: 1px solid var(–border-color); border-radius: 4px; font-size: 1rem; box-sizing: border-box; } .input-group .helper-text { font-size: 0.85em; color: #666; margin-top: 5px; } .input-group .error-message { color: #dc3545; font-size: 0.8em; margin-top: 5px; display: none; /* Hidden by default */ } .button-group { display: flex; justify-content: space-between; margin-top: 20px; flex-wrap: wrap; gap: 10px; } .button-group button { padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 1rem; transition: background-color 0.3s ease; flex: 1; min-width: 150px; } .btn-calculate { background-color: var(–primary-color); color: white; } .btn-calculate:hover { background-color: #003366; } .btn-reset { background-color: #6c757d; color: white; } .btn-reset:hover { background-color: #5a6268; } .btn-copy { background-color: #ffc107; color: #212529; } .btn-copy:hover { background-color: #e0a800; } #results-container { margin-top: 30px; padding: 20px; border: 1px solid var(–border-color); border-radius: 8px; background-color: var(–card-background); box-shadow: var(–shadow); text-align: center; } #results-container h3 { color: var(–primary-color); margin-top: 0; margin-bottom: 15px; } .result-item { margin-bottom: 10px; font-size: 1.1em; } .result-item strong { color: var(–primary-color); } .primary-result { font-size: 1.8em; font-weight: bold; color: var(–success-color); background-color: #e9ecef; padding: 15px; border-radius: 5px; margin-bottom: 15px; display: inline-block; min-width: 80%; } .formula-explanation { font-size: 0.9em; color: #555; margin-top: 15px; padding-top: 10px; border-top: 1px dashed #ccc; } table { width: 100%; border-collapse: collapse; margin-top: 20px; overflow-x: auto; /* Make table scrollable */ display: block; /* Needed for overflow-x */ white-space: nowrap; /* Prevent wrapping within cells */ } th, td { padding: 10px 15px; border: 1px solid var(–border-color); text-align: right; } th { background-color: var(–primary-color); color: white; font-weight: bold; position: sticky; top: 0; /* Stick header */ z-index: 1; } td { background-color: var(–card-background); } tr:nth-child(even) td { background-color: #f2f2f2; } caption { font-size: 1.1em; font-weight: bold; color: var(–primary-color); margin-bottom: 10px; text-align: left; } .chart-container { width: 100%; max-width: 100%; margin-top: 20px; text-align: center; background-color: var(–card-background); padding: 15px; border-radius: 8px; box-shadow: var(–shadow); } canvas { max-width: 100%; height: auto !important; /* Ensure canvas scales */ } .article-section { margin-top: 40px; padding-top: 30px; border-top: 1px solid var(–border-color); } .article-section h2, .article-section h3 { color: var(–primary-color); margin-bottom: 15px; } .article-section h2 { font-size: 1.8em; } .article-section h3 { font-size: 1.4em; } .article-section p, .article-section ul, .article-section ol { margin-bottom: 15px; } .article-section ul, .article-section ol { padding-left: 25px; } .article-section li { margin-bottom: 8px; } .faq-item { margin-bottom: 15px; padding: 10px; border-left: 3px solid var(–primary-color); background-color: #eef7ff; } .faq-item strong { display: block; color: var(–primary-color); margin-bottom: 5px; } .internal-links ul { list-style: none; padding: 0; } .internal-links li { margin-bottom: 10px; } .internal-links a { color: var(–primary-color); text-decoration: none; font-weight: bold; } .internal-links a:hover { text-decoration: underline; } .internal-links span { font-size: 0.9em; color: #555; display: block; margin-top: 3px; } @media (max-width: 768px) { .container { margin: 10px; padding: 15px; } .button-group { flex-direction: column; align-items: center; } .button-group button { width: 90%; min-width: unset; } th, td { padding: 8px 10px; font-size: 0.9em; } canvas { width: 100%; } }

Discounted Cash Flow (DCF) Calculator

Estimate the present value of future cash flows to determine investment worth.

DCF Valuation Calculator

The total upfront cost of the investment.
The required rate of return (e.g., 10 for 10%).
Enter expected cash flows for each period (e.g., 30000, 35000, 40000).

DCF Analysis Results

Net Present Value (NPV):
$0
Total Present Value of Cash Flows: 0
Number of Periods: 0
Decision: N/A
NPV = Σ [CFt / (1 + r)^t] – Initial Investment Where: CFt = Cash flow in period t, r = Discount rate, t = Time period.

What is Discounted Cash Flow (DCF)?

Discounted Cash Flow (DCF) is a valuation method used to estimate the value of an investment based on its expected future cash flows. The core principle behind DCF is that money today is worth more than the same amount of money in the future due to its potential earning capacity. Therefore, future cash flows are "discounted" back to their present value using a discount rate, which typically represents the investor's required rate of return or the cost of capital.

Who Should Use DCF?

  • Investors evaluating stocks, bonds, or real estate.
  • Businesses assessing the viability of new projects or acquisitions.
  • Financial analysts performing company valuations.
  • Anyone making long-term investment decisions where future cash generation is key.

Common Misconceptions:

  • DCF is only for large corporations: While widely used by corporations, DCF is applicable to any investment with predictable future cash flows, including small businesses and individual projects.
  • DCF provides an exact value: DCF provides an estimate. Its accuracy heavily relies on the quality of future cash flow projections and the chosen discount rate, both of which involve assumptions.
  • Higher cash flows always mean a better investment: The timing and risk associated with those cash flows, as reflected by the discount rate, are equally crucial.

Discounted Cash Flow (DCF) Formula and Mathematical Explanation

The fundamental formula for calculating the Net Present Value (NPV) using the Discounted Cash Flow method is:

NPV = Σ [ CFt / (1 + r)t ] – Initial Investment

Let's break down each component:

  • CFt (Cash Flow in Period t): This is the net cash inflow or outflow expected during a specific future period (t). For example, the profit generated by a business or the rental income from a property in a given year.
  • r (Discount Rate): This represents the rate of return required by the investor or the cost of capital for the business. It accounts for the time value of money and the risk associated with the investment. A higher discount rate implies higher risk or opportunity cost, leading to a lower present value. It's often represented as a percentage (e.g., 10% is entered as 0.10).
  • t (Time Period): This is the specific future period in which the cash flow (CFt) is expected to occur. Periods are typically years, but can also be quarters or months depending on the investment horizon.
  • Σ (Summation): This symbol indicates that we need to sum up the present values of all future cash flows across all periods (from t=1 to the end of the investment horizon).
  • Initial Investment: This is the upfront cost required to undertake the investment. It is subtracted from the total present value of future cash flows because it's an outflow occurring at time t=0.

The term CFt / (1 + r)t calculates the present value of the cash flow received in period t. By summing these discounted cash flows and subtracting the initial investment, we arrive at the Net Present Value (NPV).

Variables Table

DCF Variables Explained
Variable Meaning Unit Typical Range/Considerations
CFt Cash Flow in Period t Currency (e.g., USD, EUR) Positive (inflow) or negative (outflow). Depends on projections.
r Discount Rate Percentage (%) Typically 5% – 20%+. Reflects risk and opportunity cost (e.g., WACC).
t Time Period Years, Quarters, Months Starts from 1 for the first future period.
Initial Investment Upfront Cost Currency (e.g., USD, EUR) Usually a positive value representing cost.
NPV Net Present Value Currency (e.g., USD, EUR) Positive (investment may be profitable), Negative (investment may lose money), Zero (break-even).

Practical Examples of DCF Valuation

DCF analysis is versatile and can be applied to various investment scenarios.

Example 1: Evaluating a Small Business Acquisition

An investor is considering buying a small bakery. The purchase price (Initial Investment) is $200,000. The investor's required rate of return (Discount Rate) is 12% (0.12). They project the following net cash flows for the next five years:

  • Year 1: $40,000
  • Year 2: $45,000
  • Year 3: $50,000
  • Year 4: $55,000
  • Year 5: $60,000

Calculation:

  • PV Year 1: $40,000 / (1 + 0.12)^1 = $35,714.29
  • PV Year 2: $45,000 / (1 + 0.12)^2 = $35,830.36
  • PV Year 3: $50,000 / (1 + 0.12)^3 = $35,592.34
  • PV Year 4: $55,000 / (1 + 0.12)^4 = $35,177.70
  • PV Year 5: $60,000 / (1 + 0.12)^5 = $34,182.15

Total Present Value of Cash Flows = $35,714.29 + $35,830.36 + $35,592.34 + $35,177.70 + $34,182.15 = $176,496.84

NPV = $176,496.84 – $200,000 = -$23,503.16

Interpretation: The NPV is negative. Based purely on these projections and the required rate of return, the investment is not financially attractive as it is expected to yield less than the investor's 12% target return.

Example 2: Evaluating a New Product Launch

A tech company is considering launching a new gadget. The R&D and marketing costs (Initial Investment) are $500,000. The company uses a discount rate of 15% (0.15) for new ventures. Projected net cash flows are:

  • Year 1: $100,000
  • Year 2: $150,000
  • Year 3: $200,000
  • Year 4: $250,000
  • Year 5: $300,000

Calculation:

  • PV Year 1: $100,000 / (1 + 0.15)^1 = $86,956.52
  • PV Year 2: $150,000 / (1 + 0.15)^2 = $113,379.08
  • PV Year 3: $200,000 / (1 + 0.15)^3 = $131,501.74
  • PV Year 4: $250,000 / (1 + 0.15)^4 = $143,375.96
  • PV Year 5: $300,000 / (1 + 0.15)^5 = $149,343.91

Total Present Value of Cash Flows = $86,956.52 + $113,379.08 + $131,501.74 + $143,375.96 + $149,343.91 = $624,557.21

NPV = $624,557.21 – $500,000 = $124,557.21

Interpretation: The NPV is positive ($124,557.21). This suggests that the product launch is expected to generate returns exceeding the company's 15% required rate of return, making it a potentially worthwhile investment.

How to Use This Discounted Cash Flow Calculator

Our DCF calculator simplifies the process of estimating an investment's value. Follow these steps:

  1. Enter Initial Investment: Input the total upfront cost required for the investment. This is the money you spend at the beginning (time zero).
  2. Input Discount Rate (WACC): Enter your required rate of return or the Weighted Average Cost of Capital (WACC) as a percentage. This rate reflects the riskiness of the investment and the opportunity cost of capital. For example, enter '10' for 10%.
  3. List Future Cash Flows: Provide a comma-separated list of the expected net cash flows for each future period (e.g., year 1, year 2, year 3, etc.). Ensure the order corresponds to the time periods.
  4. Calculate: Click the "Calculate DCF" button.

How to Read Results:

  • Net Present Value (NPV): This is the primary result.
    • Positive NPV: Indicates the investment is expected to generate more value than its cost, considering the time value of money and risk. It suggests the investment may be profitable and worth pursuing.
    • Negative NPV: Suggests the investment is expected to generate less value than its cost. It may not be financially attractive at the given discount rate.
    • Zero NPV: Implies the investment is expected to earn exactly the required rate of return, breaking even in terms of value creation.
  • Total Present Value of Cash Flows: The sum of all future cash flows, discounted back to their value today.
  • Number of Periods: The total number of future periods for which cash flows were entered.
  • Decision: A simplified recommendation based on the NPV (e.g., "Approve" for positive NPV, "Reject" for negative NPV).

Decision-Making Guidance: Generally, investments with a positive NPV should be considered favorably, while those with a negative NPV should be rejected. However, always consider qualitative factors alongside the quantitative DCF analysis.

Key Factors Affecting DCF Results

The accuracy and reliability of DCF analysis depend heavily on several critical factors:

  1. Accuracy of Cash Flow Projections: This is arguably the most significant factor. Overly optimistic or pessimistic forecasts for future revenues, costs, and capital expenditures will directly skew the DCF valuation. Realistic, data-driven projections are essential.
  2. Discount Rate Selection: The discount rate (often WACC) is crucial. A small change in the discount rate can lead to a substantial change in the NPV. It must accurately reflect the investment's risk profile and the opportunity cost of capital. Using an inappropriate rate can lead to flawed decisions.
  3. Time Horizon: The number of periods for which cash flows are projected matters. Longer time horizons introduce more uncertainty. Terminal value calculations (estimating the value beyond the explicit forecast period) are often necessary for long-term investments and can significantly impact the overall valuation.
  4. Inflation Assumptions: Inflation erodes the purchasing power of future money. If cash flow projections don't account for inflation, or if the discount rate doesn't adequately incorporate an inflation premium, the resulting NPV can be misleading.
  5. Terminal Value Calculation: For investments with long lifespans, estimating a terminal value (the value of the investment beyond the explicit forecast period) is common. The method used (e.g., Gordon Growth Model, exit multiple) and its assumptions heavily influence the final DCF value.
  6. Changes in Tax Rates: Corporate taxes directly impact net cash flows. Unexpected changes in tax laws or rates can alter the profitability and thus the DCF valuation of an investment or company.
  7. Economic Conditions: Broader economic factors like interest rate changes, market growth, and regulatory shifts can significantly impact future cash flows and the appropriate discount rate, affecting the DCF outcome.

Frequently Asked Questions (FAQ) about DCF

Q1: What is the difference between DCF and NPV?

DCF is a method used to estimate an investment's value by forecasting future cash flows and discounting them back to the present. NPV is the result of the DCF calculation – it's the difference between the present value of future cash inflows and the initial investment.

Q2: Is a positive NPV always good?

Generally, yes. A positive NPV indicates that the projected earnings exceed the anticipated costs, suggesting the investment is likely to be profitable and add value. However, it should be considered alongside other strategic factors.

Q3: How do I determine the correct discount rate?

The discount rate should reflect the riskiness of the specific investment and the investor's opportunity cost. For companies, the Weighted Average Cost of Capital (WACC) is commonly used. For individual projects, a risk-adjusted rate might be applied.

Q4: What if my cash flow projections are inaccurate?

Inaccurate projections are a major limitation of DCF. Sensitivity analysis and scenario planning (best case, worst case, base case) can help assess how changes in key assumptions impact the NPV.

Q5: Can DCF be used for intangible assets?

It's challenging but possible. Valuing intangible assets like brand value or patents often requires making significant assumptions about their future cash-generating potential, making the DCF analysis more speculative.

Q6: What is the Gordon Growth Model?

The Gordon Growth Model (or Dividend Discount Model) is a method used to estimate the terminal value in a DCF analysis, assuming cash flows grow at a constant rate indefinitely. It's often used for mature, stable companies.

Q7: How many years should I project cash flows for?

There's no fixed rule. Typically, companies project cash flows for 5-10 years, followed by a terminal value calculation. The appropriate period depends on the industry, company lifecycle, and predictability of cash flows.

Q8: Does DCF account for financing costs?

Yes, indirectly. The discount rate (like WACC) incorporates the cost of debt and equity financing. If specific financing costs are tied directly to a project, they might be factored into the cash flow projections or adjusted in the discount rate.

Related Tools and Internal Resources

Present Value of Future Cash Flows Over Time

© 2023 Your Financial Website. All rights reserved.

var chartInstance = null; // Global variable to hold chart instance function validateInput(id, errorId, minValue, maxValue) { var input = document.getElementById(id); var errorElement = document.getElementById(errorId); var value = parseFloat(input.value); errorElement.style.display = 'none'; // Hide error by default if (isNaN(value)) { errorElement.textContent = "Please enter a valid number."; errorElement.style.display = 'block'; return false; } if (minValue !== undefined && value maxValue) { errorElement.textContent = "Value cannot be greater than " + maxValue + "."; errorElement.style.display = 'block'; return false; } return true; } function validateCashFlows(id, errorId) { var input = document.getElementById(id); var errorElement = document.getElementById(errorId); var rawValue = input.value.trim(); errorElement.style.display = 'none'; if (rawValue === "") { errorElement.textContent = "Please enter future cash flows."; errorElement.style.display = 'block'; return false; } var cashFlowStrings = rawValue.split(','); var cashFlows = []; for (var i = 0; i < cashFlowStrings.length; i++) { var cf = parseFloat(cashFlowStrings[i].trim()); if (isNaN(cf)) { errorElement.textContent = "Invalid cash flow value found. Ensure all values are numbers."; errorElement.style.display = 'block'; return false; } cashFlows.push(cf); } return cashFlows; } function calculateDCF() { var initialInvestmentValid = validateInput('initialInvestment', 'initialInvestmentError', 0); var discountRateValid = validateInput('discountRate', 'discountRateError', 0.1); // Min 0.1% var cashFlows = validateCashFlows('cashFlows', 'cashFlowsError'); if (!initialInvestmentValid || !discountRateValid || !cashFlows) { return; } var initialInvestment = parseFloat(document.getElementById('initialInvestment').value); var discountRate = parseFloat(document.getElementById('discountRate').value) / 100; // Convert percentage to decimal var totalPVCF = 0; var periods = cashFlows.length; var pvCashFlows = []; for (var i = 0; i 0) { decision = "Approve (Positive NPV)"; document.getElementById('npvResult').style.color = 'var(–success-color)'; } else if (npv < 0) { decision = "Reject (Negative NPV)"; document.getElementById('npvResult').style.color = '#dc3545'; } else { decision = "Neutral (Zero NPV)"; document.getElementById('npvResult').style.color = '#ffc107'; } document.getElementById('decision').textContent = decision; updateChart(pvCashFlows, initialInvestment); populateTable(cashFlows, pvCashFlows, periods); } function resetCalculator() { document.getElementById('initialInvestment').value = '100000'; document.getElementById('discountRate').value = '10'; document.getElementById('cashFlows').value = '30000, 35000, 40000, 45000, 50000'; // Clear errors document.getElementById('initialInvestmentError').style.display = 'none'; document.getElementById('discountRateError').style.display = 'none'; document.getElementById('cashFlowsError').style.display = 'none'; // Reset results document.getElementById('npvResult').textContent = '$0.00'; document.getElementById('totalPVCF').textContent = '0.00'; document.getElementById('numPeriods').textContent = '0'; document.getElementById('decision').textContent = 'N/A'; document.getElementById('npvResult').style.color = 'var(–success-color)'; // Reset color // Clear chart and table if (chartInstance) { chartInstance.destroy(); chartInstance = null; } var tableBody = document.getElementById('dcfTableBody'); if (tableBody) { tableBody.innerHTML = ''; } var canvas = document.getElementById('dcfChart'); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); } function copyResults() { var npv = document.getElementById('npvResult').textContent; var totalPVCF = document.getElementById('totalPVCF').textContent; var numPeriods = document.getElementById('numPeriods').textContent; var decision = document.getElementById('decision').textContent; var initialInvestment = document.getElementById('initialInvestment').value; var discountRate = document.getElementById('discountRate').value; var cashFlows = document.getElementById('cashFlows').value; var assumptions = "Key Assumptions:\n"; assumptions += "- Initial Investment: " + initialInvestment + "\n"; assumptions += "- Discount Rate: " + discountRate + "%\n"; assumptions += "- Cash Flows: " + cashFlows + "\n"; var resultsText = "DCF Analysis Results:\n"; resultsText += "- Net Present Value (NPV): " + npv + "\n"; resultsText += "- Total Present Value of Cash Flows: " + totalPVCF + "\n"; resultsText += "- Number of Periods: " + numPeriods + "\n"; resultsText += "- Decision: " + decision + "\n\n"; resultsText += assumptions; // Use navigator.clipboard for modern browsers if (navigator.clipboard && window.isSecureContext) { navigator.clipboard.writeText(resultsText).then(function() { alert('Results copied to clipboard!'); }).catch(function(err) { console.error('Failed to copy: ', err); fallbackCopyTextToClipboard(resultsText); }); } else { fallbackCopyTextToClipboard(resultsText); } } // Fallback for older browsers or non-HTTPS contexts function fallbackCopyTextToClipboard(text) { var textArea = document.createElement("textarea"); textArea.value = text; textArea.style.position = "fixed"; // Avoid scrolling to bottom textArea.style.left = "-9999px"; textArea.style.top = "-9999px"; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Fallback: Copying text command was ' + msg); alert('Results copied to clipboard!'); } catch (err) { console.error('Fallback: Oops, unable to copy', err); alert('Failed to copy results. Please copy manually.'); } document.body.removeChild(textArea); } function populateTable(cashFlows, pvCashFlows, periods) { var tableBody = document.getElementById('dcfTableBody'); if (!tableBody) { var table = document.createElement('table'); table.id = 'dcfTable'; table.innerHTML = ` Cash Flow Discounting Details Period (t) Future Cash Flow (CFt) Discount Rate (r) Discount Factor (1+r)^t Present Value (PV) `; document.querySelector('.calculator-section').appendChild(table); tableBody = document.getElementById('dcfTableBody'); } else { tableBody.innerHTML = "; // Clear existing rows if table already exists } var discountRate = parseFloat(document.getElementById('discountRate').value) / 100; for (var i = 0; i < periods; i++) { var period = i + 1; var cf = cashFlows[i]; var discountFactor = Math.pow(1 + discountRate, period); var pv = pvCashFlows[i]; var row = tableBody.insertRow(); row.insertCell(0).textContent = period; row.insertCell(1).textContent = '$' + cf.toFixed(2); row.insertCell(2).textContent = (discountRate * 100).toFixed(1) + '%'; row.insertCell(3).textContent = discountFactor.toFixed(4); row.insertCell(4).textContent = '$' + pv.toFixed(2); } } function updateChart(pvCashFlows, initialInvestment) { var ctx = document.getElementById('dcfChart').getContext('2d'); // Destroy previous chart instance if it exists if (chartInstance) { chartInstance.destroy(); } var labels = []; for (var i = 0; i < pvCashFlows.length; i++) { labels.push('Year ' + (i + 1)); } var data = { labels: labels, datasets: [ { label: 'Present Value of Cash Flow', data: pvCashFlows, borderColor: 'var(–primary-color)', backgroundColor: 'rgba(0, 74, 153, 0.2)', fill: true, tension: 0.1 }, { label: 'Initial Investment (Negative)', data: Array(pvCashFlows.length).fill(-initialInvestment / pvCashFlows.length), // Distribute initial investment across periods for visualization borderColor: '#dc3545', backgroundColor: 'rgba(220, 53, 69, 0.2)', fill: false, tension: 0.1, borderDash: [5, 5] // Dashed line for investment } ] }; var chartOptions = { responsive: true, maintainAspectRatio: false, // Allows custom height/width scales: { y: { beginAtZero: false, // Adjust based on data range title: { display: true, text: 'Value (in $)' } }, x: { title: { display: true, text: 'Time Period' } } }, plugins: { tooltip: { callbacks: { label: function(context) { var label = context.dataset.label || ''; if (label) { label += ': '; } if (context.parsed.y !== null) { label += new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(context.parsed.y); } return label; } } } } }; // Dynamically set canvas height based on container width for better aspect ratio var canvasContainer = document.querySelector('.chart-container'); var canvas = document.getElementById('dcfChart'); var aspectRatio = 0.5; // Adjust this ratio as needed (e.g., 0.5 for a wider chart) canvas.height = canvasContainer.offsetWidth * aspectRatio; chartInstance = new Chart(ctx, { type: 'line', data: data, options: chartOptions }); } // Initial calculation on page load document.addEventListener('DOMContentLoaded', function() { calculateDCF(); // Ensure chart canvas is correctly sized on load window.dispatchEvent(new Event('resize')); }); // Re-calculate on window resize to adjust chart window.addEventListener('resize', function() { if (chartInstance) { var canvasContainer = document.querySelector('.chart-container'); var canvas = document.getElementById('dcfChart'); var aspectRatio = 0.5; canvas.height = canvasContainer.offsetWidth * aspectRatio; chartInstance.resize(); } }); <!– NOTE: The Chart.js library is required for the chart to function. You would typically include it via a CDN like this: For this standalone HTML file, it's assumed Chart.js is available globally. If running this file directly, you'll need to add the Chart.js CDN link. –>

Leave a Comment