Skip to content

feat: enhance Amount class with Big.js integration - #73

Merged
Gaubee merged 1 commit into
mainfrom
feat/amount-enhance
Dec 22, 2025
Merged

Gaubee merged 1 commit into
mainfrom
feat/amount-enhance

Conversation

@Gaubee

@Gaubee Gaubee commented Dec 22, 2025

Copy link
Copy Markdown
Contributor

Part of #63, Closes #64

变更

集成 Big.js 进行精确的十进制计算,并添加多项新功能。

Big.js 集成

  • 底层使用 Big.js 替代 bigint 进行计算
  • 消除浮点数精度问题
  • 支持任意精度的小数运算

序列化支持

const amount = Amount.fromFormatted('1.5', 18, 'ETH')
const json = amount.toJSON()
// { raw: '1500000000000000000', decimals: 18, symbol: 'ETH' }

const restored = Amount.fromJSON(json)

格式化显示

const amount = Amount.fromFormatted('1234567.89', 8)
amount.toDisplayString({ locale: 'en-US' })
// '1,234,567.89'

精度转换

const usdc = Amount.fromRaw('1000000', 6)  // 1 USDC (6 decimals)
const converted = usdc.toDecimals(18)      // 18 decimals
converted.toFormatted() // '1'

新增方法

  • toJSON() / fromJSON() - 序列化
  • toDisplayString() - 带千分位的显示
  • toDecimals() - 精度转换
  • withAsset() - 从资产信息创建
  • percent() - 百分比计算
  • mod(), abs(), neg() - 更多运算
  • isAmount() - 类型守卫
  • toAmount() - 安全转换

测试

63 个测试用例全部通过。

Part of #63, Closes #64

Changes:
- Integrate Big.js for precise decimal calculations
- Add serialization: toJSON() / fromJSON()
- Add toDisplayString() for locale-aware formatting
- Add toDecimals() for precision conversion
- Add withAsset() for asset integration
- Add percent(), mod(), abs(), neg() operations
- Add isAmount() type guard and toAmount() helper

API additions:
- Amount.fromJSON(json): Deserialize from JSON
- amount.toJSON(): Serialize to JSON
- amount.toDisplayString({ locale, fractionDigits })
- amount.toDecimals(newDecimals): Convert precision
- amount.withAsset({ decimals, assetType })
- amount.percent(5): Calculate 5%
- amount.mod(n), amount.abs(), amount.neg()
- isAmount(value): Type guard
- toAmount(value, decimals, symbol): Safe conversion
@Gaubee
Gaubee merged commit 249149b into main Dec 22, 2025
3 checks passed
@Gaubee Gaubee mentioned this pull request Dec 22, 2025
1 of 10 tasks
@Gaubee
Gaubee deleted the feat/amount-enhance branch January 4, 2026 07:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

增强 Amount 类:Big.js 集成 + 序列化支持

1 participant