Currency Conversion for E-commerce site - Preventing incorrect Total Cart due to rounding

不羁岁月 提交于 2019-12-06 01:30:29

I'm firmly in the 1 camp. Currency conversion is core business logic, and belongs in your models, not your views.

Further, although money looks like floating-point numbers, it isn't. Money changes hands in integer quantities of whatever your base unit is. In the US, for example, If gumballs are 10 cents each and I buy ten, then I'm trading 100 pennies for 10 gumballs. Even if I give a dollar bill, from a software perspective, it's best to count that as 100 pennies.

For more on this, see Martin Fowler's "Patterns of Enterprise Application Architecture" and "Analysis Patterns". He talks through all the issues in detail and gives good sample code. You can also find some of that info on the web:

  • Quantity (with some money sample code)
  • Money (mainly a pointer into his book)

If you need the accounting to work, I'd also talk to the accountant. Currency conversion is often complicated by changing rates, weird fees, and other nonsense, and you can spend a long time chasing pennies to make the books balance if you don't get it right from the get-go.

If you are billing based on the converted currency, you really shouldn't be doing that calculation in your view logic.

Well personally, I would just make the total amount, the subtotal added to the ship amount. This is obviously the simplest method to use, and no-one will miss the extra penny.

Don't use floating point numbers for money, ever! You are letting yourself into a world of hurt with rounding for no good reason. Since PHP doesn't have a decimal fixed point type, do all money calculations with integers. See William's links.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!