Ошибка в коде калькулятора сложного процента
Считает максимально ерунду какую-то. Я начинающий, поэтому ошибку не получается выловить. Суть в том, что даже если задать простейшие нач. значения, числа увеличиваются на десятые доли. Например: берем капитал 100, процент 5 и срок 1 год. на выходе: 105.12, хотя должно быть 105. Если использовать нач. значения сложнее, вообще логику результата уловить не могу. Надеюсь на помощь)
document.addEventListener("DOMContentLoaded", function() {
var myChart = null;
function calculate() {
var principal = parseFloat(document.getElementById('principal').value) || 0;
var rate = parseFloat(document.getElementById('rate').value) || 0;
var time = parseFloat(document.getElementById('time').value) || 0;
var timeType = document.getElementById('timeType').value;
var monthly = parseFloat(document.getElementById('monthly').value) || 0;
var inflation = parseFloat(document.getElementById('inflation').value) || 0;
if (timeType === 'years') {
time *= 12;
}
rate = rate / 100 / 12; // Convert annual rate to monthly and percentage
inflation = inflation / 100;
var total = principal;
var data = [];
var labels = [];
for (var i = 0; i <= time; i++) {
if (i !== 0) {
total += monthly + (total * rate);
}
var inflationAdjustedTotal = total / Math.pow(1 + inflation, i / 12);
data.push(inflationAdjustedTotal.toFixed(2));
labels.push(i);
}
var result = data[data.length - 1];
document.getElementById('result').innerHTML = 'Итоговая сумма: ' + result;
updateChart(labels, data);
}
function updateChart(labels, data) {
var ctx = document.getElementById('chart').getContext('2d');
var graphType = document.getElementById('graphType').value;
if (myChart) {
myChart.destroy();
}
var adjustedData = [];
var adjustedLabels = [];
if (graphType === 'years') {
for (var i = 0; i < labels.length; i += 12) {
adjustedLabels.push(labels[i] / 12);
adjustedData.push(data[i]);
}
} else {
adjustedLabels = labels;
adjustedData = data;
}
myChart = new Chart(ctx, {
type: 'line',
data: {
labels: adjustedLabels,
datasets: [{
label: 'Рост накоплений с учетом инфляции',
data: adjustedData,
fill: false,
borderColor: '#ff845f',
borderWidth: 2,
pointRadius: 4,
pointHoverRadius: 6,
pointBackgroundColor: '#ff845f',
}]
},
options: {
scales: {
x: {
type: 'linear',
title: {
display: true,
text: 'Время (' + (graphType === 'years' ? 'Годы' : 'Месяцы') + ')'
}
},
y: {
type: 'linear',
title: {
display: true,
text: 'Сумма'
}
}
}
}
});
}
document.getElementById('calculate-button').addEventListener('click', calculate);
document.getElementById('graphType').addEventListener('change', calculate);
});
body {
font-family: Arial, sans-serif;
}
.container {
display: flex;
flex-wrap: wrap;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.calculator, .chart-section {
flex: 1;
margin-right: 20px;
}
.input-field {
margin: 10px 0;
}
.input-field label {
display: block;
margin-bottom: 5px;
}
.input-field input, .input-field select {
padding: 10px;
width: 100%;
box-sizing: border-box;
}
.result {
margin-top: 20px;
font-size: 20px;
font-weight: bold;
}
.calculate-button {
background-color: #ff845f;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
outline: none;
}
.chart-container {
max-width: 800px;
width: 100%;
height: 400px;
margin-top: 20px;
}
<body>
<div class="container">
<div class="calculator">
<div class="input-field">
<label for="principal">Начальный капитал:</label>
<input type="number" id="principal">
</div>
<div class="input-field">
<label for="rate">Процентная ставка (в год):</label>
<input type="number" id="rate">
</div>
<div class="input-field">
<label for="time">Срок:</label>
<input type="number" id="time">
</div>
<div class="input-field">
<label for="timeType">Тип срока:</label>
<select id="timeType">
<option value="years">Годы</option>
<option value="months">Месяцы</option>
</select>
</div>
<div class="input-field">
<label for="monthly">Ежемесячные вложения:</label>
<input type="number" id="monthly">
</div>
<div class="input-field">
<label for="inflation">Среднегодовая инфляция:</label>
<input type="number" id="inflation" value="0">
</div>
<button class="calculate-button" id="calculate-button">Рассчитать</button>
<div class="result" id="result"></div>
</div>
<div class="chart-section">
<div class="chart-container">
<canvas id="chart"></canvas>
</div>
<div class="input-field">
<label for="graphType">Отображение графика:</label>
<select id="graphType">
<option value="months">Месяцы</option>
<option value="years">Годы</option>
</select>
</div>
</div>
</div>