首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >计算价格的javascript小算法

计算价格的javascript小算法
EN

Stack Overflow用户
提问于 2015-03-06 18:43:41
回答 3查看 432关注 0票数 0

我正在开发一个小网站,我有20个产品销售。

每周我都想计算每一种产品的新价格,同时考虑到每种产品的销售数量,但要遵循两条规则:

  • 这20种产品的价格之和必须总是100欧元。
  • 我希望每个产品都是整数(不包括十进制),或者是.5,我的意思是,一个产品的价格可以是7、8、9、7.5或8.5,但不是8.3或7.1。

让我们举个例子,但用4种产品进行简化:

本周销售:

代码语言:javascript
运行
复制
product_id  sells
----------  ------
     1       45
     2       31
     3       12
     4       62

好的,那么总销量是150。

如果我把那100欧元除以150欧元,我就能得到0.667欧元一份。所以,如果我把每一个产品乘以我得到的这个值:

代码语言:javascript
运行
复制
product_id  sells  raw_price_next_week
----------  ------  -------------------
     1       45             30.015
     2       31             20.677
     3       12             8.004
     4       62             41.354

然后,我需要标准化这些raw_prices,考虑到我前面提到的第二条规则,得到每个raw_value最接近的0.5倍.

代码语言:javascript
运行
复制
product_id  sells  raw_price_next_week    final_price
----------  ------  -------------------    ------------
     1       45             30.015             30
     2       31             20.677             20.5
     3       12             8.004              8
     4       62             41.354             41.5

我一直在考虑如何编码这个小部分,但事实是,我甚至不知道如何开始。我需要一些专家帮助..。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-03-06 19:52:56

不确定是否需要实际显示已完成的结果,但这应该提供正确的计算。

代码语言:javascript
运行
复制
// Start with the raw product data (array of object - from database likely)
    var 
        products = [
            {
                product_id: 1,
                sells: 45
            },
            {
                product_id: 2,
                sells: 31
            },
            {
                product_id: 3,
                sells: 12
            },
            {
                product_id: 4,
                sells: 62
            }
        ]
    ;
    
    // ###############################################################
    
    window.Pricing = {
        
        total_sum: 100, // This represents the 100€
        sales : 0,
        
        init: function( products ) {     
            return this.calculate_final_price( products );
        },
           
        get_price_per_sale: function( products ) {
    
            for( x in products ) {
                this.sales += products[x].sells;        
            }
            
            return this.total_sum / this.sales;                
        },
        
        calculate_final_price: function( products ) {
                    
            var price_per_sale = this.get_price_per_sale( products );
            
            for( x in products ) {
                products[x].raw_price_next_week = +( products[x].sells * price_per_sale );
                products[x].final_price = +( Math.round( products[x].raw_price_next_week * 2 ) / 2 ).toFixed(1);        
            }
            
            return products;
        }
        
    };
    
    // ###############################################################
    
    // Init the pricing calculations and get the final objects with updated pricing.
    Pricing.init( products );

小提琴:http://jsfiddle.net/0nbbojp9/1/

票数 1
EN

Stack Overflow用户

发布于 2015-03-06 19:45:03

好的,这就是我在javascript中想出的,正如你所要求的。此外,您还可以测试它的这里

代码语言:javascript
运行
复制
// 1.) Set array for product prices... I just put a random number of products
var productPrices = [10,20,20,30,30,30,25,10];

// 2.) Get initial total price to calculate price change
var productPriceSum = 0;
for (var i = 0; i < productPrices.length; i++) {
    productPriceSum += productPrices[i];
}
var priceChange = (100/productPriceSum);

// 3.) Change prices rounding to the nearest .5
productPriceSum = 0;
for (var i = 0; i < productPrices.length; i++) {
    var newPrice = Math.round((productPrices[i]*priceChange)*10)/10
    var npDecimal = (newPrice - Math.floor(newPrice))
    if(npDecimal < 0.5){
        newPrice = Math.floor(newPrice)
    }else{
        newPrice = Math.floor(newPrice) + .5
    }
    productPrices[i] = newPrice;
    productPriceSum += newPrice;
}

// 4.) Account for any missing or excess of numbers to get the total back to 100
var makeEvenHundred = (100 - productPriceSum)
for(var i = 0; i < (makeEvenHundred*2); i ++){
    if(makeEvenHundred < 0){
        productPrices[i] -= .5
    }else{
        productPrices[i] += .5
    }
}

// Proof it all worked!
productPriceSum = 0;
for (var i = 0; i < productPrices.length; i++) {
    alert('Product # ' + (i+1) + ' Price: ' + productPrices[i]);
    productPriceSum += productPrices[i];
}
alert('Total: ' + productPriceSum);

另外,请注意,第4节可能需要调整,但是您希望逻辑在那里工作。我把它放在一起的方式,它将增加或删除的第一个价格的价值,直到总数已回到100。此外,它还假设实际上有足够的产品一次添加或删除.5 (您说了20,所以我假设这是可行的)。

所以,如果这个网站是成功的,只要知道我为你做了所有的工作;)

票数 0
EN

Stack Overflow用户

发布于 2015-03-06 20:22:54

解决方案

诀窍是把问题分解成小块,分别处理每个问题。详细情况如下:

  1. 将值舍入最近的整数。
  2. 捕获十进制值。
  3. 除以十进制值,看看有多少'0.5's构成这个值。
  4. 乘以0.5的个数,得到最接近的0.5值。
  5. 将1的值和4的值相加。

您也可以将closest变量调整为不同的值。

下面是这方面的实施情况。可以使用map函数对数据数组中的所有值执行normalization。在您的例子中,这将是一些ajax调用的结果。

实现

代码语言:javascript
运行
复制
var data = [30.015, 20.677, 8.004, 41.354];

function normalize(value) {
  var closest = 0.5;
  var significand = Math.floor(value);
  var mantissa = (value % 1).toFixed(2);
  var normalized = Math.round(mantissa / closest) * closest;
  return significand + normalized;
}

var normalized = data.map(normalize);

console.log(normalized);
代码语言:javascript
运行
复制
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

资源

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28905519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档