82 lines
1.8 KiB
TypeScript
82 lines
1.8 KiB
TypeScript
import Decimal from 'decimal.js';
|
|
|
|
/**
|
|
* 积分股数量值对象
|
|
* 支持高精度计算
|
|
*/
|
|
export class ShareAmount {
|
|
private readonly _value: Decimal;
|
|
|
|
constructor(value: Decimal | string | number) {
|
|
if (value instanceof Decimal) {
|
|
this._value = value;
|
|
} else {
|
|
this._value = new Decimal(value);
|
|
}
|
|
|
|
if (this._value.isNegative()) {
|
|
throw new Error('Share amount cannot be negative');
|
|
}
|
|
}
|
|
|
|
get value(): Decimal {
|
|
return this._value;
|
|
}
|
|
|
|
add(other: ShareAmount): ShareAmount {
|
|
return new ShareAmount(this._value.plus(other._value));
|
|
}
|
|
|
|
subtract(other: ShareAmount): ShareAmount {
|
|
const result = this._value.minus(other._value);
|
|
if (result.isNegative()) {
|
|
throw new Error('Insufficient share amount');
|
|
}
|
|
return new ShareAmount(result);
|
|
}
|
|
|
|
multiply(factor: Decimal | string | number): ShareAmount {
|
|
return new ShareAmount(this._value.times(factor));
|
|
}
|
|
|
|
divide(divisor: Decimal | string | number): ShareAmount {
|
|
return new ShareAmount(this._value.dividedBy(divisor));
|
|
}
|
|
|
|
isZero(): boolean {
|
|
return this._value.isZero();
|
|
}
|
|
|
|
isGreaterThan(other: ShareAmount): boolean {
|
|
return this._value.greaterThan(other._value);
|
|
}
|
|
|
|
isLessThan(other: ShareAmount): boolean {
|
|
return this._value.lessThan(other._value);
|
|
}
|
|
|
|
isGreaterThanOrEqual(other: ShareAmount): boolean {
|
|
return this._value.greaterThanOrEqualTo(other._value);
|
|
}
|
|
|
|
equals(other: ShareAmount): boolean {
|
|
return this._value.equals(other._value);
|
|
}
|
|
|
|
toFixed(decimals: number = 8): string {
|
|
return this._value.toFixed(decimals);
|
|
}
|
|
|
|
toString(): string {
|
|
return this._value.toString();
|
|
}
|
|
|
|
static zero(): ShareAmount {
|
|
return new ShareAmount(0);
|
|
}
|
|
|
|
static fromString(value: string): ShareAmount {
|
|
return new ShareAmount(value);
|
|
}
|
|
}
|