英文:
What type to use to correctly handle division of odd numbers of cents? (or smallest units of any currency)
问题
大多数时候,我看到建议将货币表示为其最基本的单位,并使用64位无符号整数以提供最大容量。
表面上看起来没问题,但如果我想分割1分钱怎么办?
在Java/Scala中,我也看到推荐使用BigDecimal类型来处理货币,它可以跟踪到一分钱的小数,0.01/2 = 0.005
但是,如果将一个64位无符号整数除以2,1/2 = 0
我正在尝试编写一些处理货币的Go代码,并想知道应该使用哪种类型(只使用uint64还是找其他类型)。
谢谢!
英文:
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!
答案1
得分: 3
你可以使用big.Rat
来处理任意大小的有理数。这样,你可以随心所欲地拆分数量,而不会失去任何精度。
英文:
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.
答案2
得分: 3
int64
(或uint64
)仍然可以用于表示带有分数的货币金额。例如,如果您要处理的最小金额是0.01
美分,那么您可以将1
美分表示为100
,那么半美分将为50
,1/100
美分将为1
。这种表示方法非常高效(从性能和内存使用的角度来看),但不太灵活。需要注意的事项包括:
- 使用此方法可以表示的最大值为(约为
~2^64/100
美分) - 如果最大精度发生变化,将需要对应用程序及其存储的数据进行更改
- 所有算术运算都需要谨慎实现,考虑四舍五入的影响
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论