1

我有 24 个价格,一天中每个小时一个价格,我需要找到它们的平均值(每日平均值)。

但是,我无法正确地平均价格,也找不到关于如何在 Javascript 中平均价格/四舍五入的准确算法。每种方法(parseFloat、toFixed())似乎偶尔会产生不准确的结果。

有谁知道 Javascript 中平均价格/四舍五入的准确方法?而且我不只是在谈论仅适用于以下价格数组的东西,而是适用于任何价格数组(小数)的有效且防弹的东西......

这是我现在所拥有的。它在 Chrome 中返回 178.00。但它应该返回 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);
4

2 回答 2

3

Please refer to this question https://stackoverflow.com/a/588014/536984

JavaScript floating point math is not meant to do finance calculations, also is better that you represent your prices in cents, that way you don't have decimals

var array = [2340, 2440, 2468, 2500, 2510, 3081, 85119, 64647, 65924, 70770, 75923, 12469, 3793, 5325, 2340, 2380, 2340, 2340, 5057, 3778, 2500, 2455, 2340, 2373];

Math.round(array.reduce(function (a, b) { return a + b }) / array.length)
于 2014-03-30T05:16:34.617 回答
1

正如在别处所说,使用整数最容易获得金钱,但要精确到半美分,请在将总数除以价格数量除以100 再次得到美分。

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];

var total=prices.map(function(n){
    return n*100;
}).reduce(function(a, b){
    return a+(b || 0);
});

Math.round((total/prices.length))/100;

/*  returned value: (Number)
178.01
*/
于 2014-03-30T06:10:46.440 回答