I have 24 prices, one price for each hour of the day, and I need to find the average for them (the daily average).
But, I can't get the prices to average correctly, and I can't find an accurate algorithm on how to average prices/round decimals in Javascript. Every method (parseFloat, toFixed()) seems to produce inaccurate results occasionally.
Does anyone know the ACCURATE way to average prices/round decimals in Javascript? And I'm not just talking about something that works only with the array of prices below, but something that works and is bullet-proof with any array of prices (decimals)...
Here is what I have right now. It returns 178.00 in Chrome. But it should return 178.01.
// Rounding Function
function roundDecimal(value) {
return Number(Math.round(value+'e2')+'e-2');
};
var priceSum = 0;
var prices = [23.4,24.4,24.68,25,25.1,30.81,851.19,646.47,659.24,707.7,759.23,124.69,37.93,53.25,23.4,23.8,23.4,23.4,50.57,37.78,25,24.55,23.4,23.73]
for(var x = 0; x < prices.length; x ++) {
priceSum = priceSum + prices[x];
console.log(priceSum);
};
var priceAverage = roundDecimal( priceSum / prices.length );
console.log("Daily Average is: "+priceAverage);