drb0901500211 2015-12-10 16:08
浏览 95
已采纳

购物篮四舍五入

I'm trying to find the best way to calculate basket's prices and totals. All product prices are represented by figures with 2 decimal points, however, when discount is added to the basket of say 50%, this given for instance price of $37.27 ends up with figure $18.635 having 3 decimal places. Now I'd like the calculations to be accurate, but rounding 3 decimal figures doesn't always give the expected result.

Scenario

I have 5 products in my basket with the following, original prices:

  • $80.00
  • $189.62
  • $37.27
  • $43.75
  • $105.34

Giving us total of $455.98

When I add a global discount of 50% - taking the total of figures above, this would give me $227.99. Now, this would work fine if I don't have to obtain the figure for each item after the discount has been applied - and that is the case when I want to pass the items to the PayPal Express Checkout. Request will fail unless total equals total of all items in the basket.

The above figures after dividing each by 2 (50%) are:

  • $40.00
  • $94.81
  • $18.635
  • $21.875
  • $52.67

Giving us precisely same total as when we divide the total by 2. Problem is that I do not want 3 decimal figures in my basket, so rounding them the result becomes:

  • $40.00
  • $94.81
  • $18.64
  • $21.88
  • $52.67

which adds up to $228, which when multiplied by 2 gives us a different figure to the one we originally had in the basket without discount being applied.

What is the best way to tackle this sort of scenarios?

  • 写回答

2条回答 默认 最新

  • dpwdsmbvm496180204 2015-12-11 20:31
    关注

    this is such a great question. my vote would be to apply the 50% discount to each item - round that number to 2 decimal places with number format - and save that number as part of the cart order record even if you aren't showing to customer. then add those figures up like normal to get the cart product total.

    reason: someone at some point is going to need a clear amount that was charged for each product. AND think about returns. its going to make returns so much easier if you aren't having to correct for .01 differences.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错