使用哪种类型来正确处理美分的奇数除法? (或任何货币的最小单位)

Most of the time I see recommendations to represent money as its most fundamental unit; and to use 64 bit unsigned integer to provide maximal capacity.

On the surface this seems fine, but what about the case where I want to split 1 cent?

In Java/Scala the BigDecimal type, which I also see recommended for handling money, will track fractions of a cent, 0.01/2 = 0.005

But dividing a 64 bit unsigned int, 1/2 = 0

I'm trying to write some Go that handles money, and want to know which type to use (just use uint64 or find something else?).

Thank you!

You can use big.Rat for rational numbers of arbitrary size. Then you can split quantities to your heart's content without losing any precision.

int64 (or uint64) still can be used to represent monetary amounts with cent fractions. E.g. if the minimum amount that you want to operate with is 0.01 cents then you can represent 1 cent as 100, then half a cent will be 50 and 1/100 of a cent will be 1. This representation is very efficient (from performance and memory usage point of view) but not very flexible. Things to be aware of are:

  • there is maximum value (~2^64/100 cents) that you can represent using this method
  • changes will be required to the app and its stored data if the maximum precision changes
  • all arithmetic operations needs to be carefully implemented taking rounding into account