jasagregoric
jasagregoric

Reputation: 63

JavaScript: Precision with Numeric Data

I'm working on a web application that involves dynamic table creation and data synchronization using JavaScript, CSS, and HTML. The application allows users to input values, which are then displayed in a table. Those values are then multiplied, etc. I'm supposed to get value like this 1023.60 but instead I get value like this 1023.5999999999999

I've tried using .toFixed(2) and making it a string and then cutting number 2 spots behind ..

Here is my JS code:

const purchasedStocks = [];
let val = 0;

document.addEventListener("DOMContentLoaded", function() {
  const sessionCells = JSON.parse(sessionStorage.getItem('sessionCells')) || [];
  const table = document.getElementById('portTable');
  sessionCells.forEach(function(cell) {
    createCells(cell.nameSMCI, parseFloat(cell.valueSMCI).toFixed(2)); 
  
  const hasSMCI = sessionCells.some(function(cell) {
    return cell.nameSMCI === "SMCI";
  });
    
  if (hasSMCI) {
    const matchingCell = sessionCells.find(cell => cell.nameSMCI === "SMCI");

    purchasedStocks.push([
      matchingCell.nameSMCI,
      matchingCell.valueSMCI,
      matchingCell.stockSMCI,
      matchingCell.priceSMCI,
      matchingCell.sumSMCI,
      matchingCell.countSMCI
    ]);
  }
  
});

document.addEventListener("DOMContentLoaded", function() {
  });
  document.getElementById("overlaySubmitSMCI").addEventListener("click", function () {
    event.preventDefault();
    cFunction();
    const overlay = document.getElementById('overlay');
    overlay.style.display = 'none';
    
    const price = data.SMCI.number;
    const inputField = document.getElementById("stockInput");
    let stock = 0;
    let value = 0;

    if (val == 0) {
      stock = (inputField.valueAsNumber / price).toFixed(2);
      value = inputField.valueAsNumber.toFixed(2);
    } else {
      stock = inputField.valueAsNumber.toFixed(2);
      value = (inputField.valueAsNumber * price).toFixed(2);
    }

    if(hasEntry(purchasedStocks, "SMCI")== -1) {
      purchasedStocks.push(["SMCI", value, stock, price, price, 1]);
      createCells("SMCI", value);

      sessionCells.push({ nameSMCI: "SMCI", valueSMCI: value, stockSMCI: stock, priceSMCI: price, sumSmci: price, countSMCI: 1 });
      sessionStorage.setItem('sessionCells', JSON.stringify(sessionCells));
    }
    else{
      $i=hasEntry(purchasedStocks, "SMCI");
      purchasedStocks[$i][1]=parseFloat(purchasedStocks[$i][1])+parseFloat(value);
      purchasedStocks[$i][3]=addValueAndCalculateAverage(parseFloat(price), parseFloat(purchasedStocks[$i][4]), parseFloat(purchasedStocks[$i][5]));
      purchasedStocks[$i][2]=parseFloat(purchasedStocks[$i][2])+parseFloat(stock);
      purchasedStocks[$i][4]=parseFloat(price)+parseFloat(purchasedStocks[$i][4]);
      purchasedStocks[$i][5]=parseFloat(purchasedStocks[$i][5])+1;

      const cell = document.getElementById('cell2SMCI');
      cell.textContent = parseFloat(purchasedStocks[$i][1]);

      const existingEntry = sessionCells.find(entry => entry.nameSMCI === "SMCI");
      existingEntry.valueSMCI = purchasedStocks[$i][1];
      existingEntry.stockSMCI = purchasedStocks[$i][2];
      existingEntry.priceSMCI = purchasedStocks[$i][3];
      existingEntry.sumSMCI = purchasedStocks[$i][4];
      existingEntry.countSMCI = purchasedStocks[$i][5];

      sessionStorage.setItem('sessionCells', JSON.stringify(sessionCells));
    }
  });
});

function cFunction() {
  Swal.fire({
    title: '<span style="color: white;">Credits!<span>',
    html: '<div style=line-height: 25px;"><span style="color: white;">Author: Jaša Gregorič<br>Date: November 2023<br>Mentor: Boštjan Vouk</span></div>',
    icon: 'info',
    confirmButtonText: 'OK',
    iconColor: 'white',
    background: '#1d1d1d',
    heightAuto: false
  });
}

function createCells($n, $v){
  const table = document.getElementById('portTable');
  const newRow = document.createElement('tr');
  const newCell1 = document.createElement('td');
  newCell1.textContent = $n;
  newCell1.setAttribute('id', ("cell1"+$n));
  const newCell2 = document.createElement('td');
  newCell2.textContent = numberToString(parseFloat($v).toFixed(2));
  newCell2.setAttribute('id', ("cell2"+$n));

  newRow.appendChild(newCell1);
  newRow.appendChild(newCell2);

  table.appendChild(newRow);
  localStorage.setItem('myTableHTML', table.innerHTML);
}

function addValueAndCalculateAverage(newValue, sum, count) {
  count++;
  sum += newValue;
  const newAverage = sum / count; 
  return newAverage;
}

function numberToString(inputNumber) {
  const numberString = inputNumber.toString();
  const parts = numberString.split('.');
  
  return parts[0] + '.' + parts[1].substring(0, 2);
}

Upvotes: 0

Views: 35

Answers (0)

Related Questions