What are the downsides to storing money values as cents / minor units?

后端 未结 3 1498
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 05:37

I have noticed that some financial api\'s like stripe api for credit card processing require that amounts be passed in as cents, this seems like a good simplification and it is

3条回答
  •  无人共我
    2021-02-05 06:03

    The downside is that you can't represent fractional units. This is a problem if you are performing interest calculations or the like. However, if you are making a "real money" transaction, this issue goes away.

    It doesn't matter if the currency is non-decimal - as long as there is a smallest unit, you can use that to represent any other amount. You may need to be a little more clever in how you display in human readable format, if that is relevant, but that's a separate issue.

    In fact, using the smallest unit is likely to simplify performing conversions, as you can work out the conversion rate between the smallest unit of each currency pair. Of course, once you're into conversion rates, you'll end up needing to use BigDecimal (or the like) again.

    So, in summary, it may well be best to use both smallest unit as your denomination, AND to use BigDecimal to handle fractional parts if they can arise. Don't use IEEE floats, because they can't represent all decimal numbers correctly. This will lead to the kinds of errors that will upset someone.

提交回复
热议问题