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 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)