Skip to content

分存元算方案


分存元算方案业界主流的高性能金额处理方案。

金额存储和计算全用 long(单位:分),只在展示层转成元:

// 存储:1999 分
long priceInCents = 1999L;
// 展示:19.99 元
String display = String.format("%.2f", priceInCents / 100.0);

整数运算没有精度问题,性能也是最优的。

public class Money {
private final long cents;
public Money(long cents) {
this.cents = cents;
}
public Money add(Money other) {
return new Money(this.cents + other.cents);
}
public Money multiply(int quantity) {
return new Money(this.cents * quantity);
}
// 展示用
public String toYuanString() {
return String.format("%.2f", cents / 100.0);
}
}
// long 最大值约 922 亿亿分 = 92 万亿元
// 正常业务不会溢出,但批量汇总时要留意
long total = orders.stream().mapToLong(Order::getAmountCents).sum();
// 100 分平分给 3 人
long each = 100 / 3; // 33 分
long remainder = 100 % 3; // 1 分
// 通常做法:最后一人承担余数
// 33 + 33 + 34 = 100

余数怎么处理是业务决策问题。

支付宝、微信支付的接口金额单位就是分,数据库里存分值,这套方案经过海量交易验证。