fix: parseAmountToInt支持尾随0了

This commit is contained in:
2026-01-09 11:15:15 +08:00
parent 25d3865a6c
commit 0c6e642a33

View File

@@ -9,16 +9,27 @@ export function parseAmountToInt(amountStr: string, precision: number): bigint {
// 例:"123.45", precision=2 → 12345n
// 例:"0.00001234", precision=8 → 1234n
const [intPart, fracPart = ""] = amountStr.split(".")
// 去掉正负号处理(如不需要可删)
const negative = amountStr.startsWith("-")
const normalizedStr = negative ? amountStr.slice(1) : amountStr
if (fracPart.length > precision) {
throw new Error(`Amount ${amountStr} exceeds precision ${precision}`)
const [intPart, fracRaw = ""] = normalizedStr.split(".")
// 关键修复点:允许尾随 0
const fracTrimmed = fracRaw.replace(/0+$/, "")
if (fracTrimmed.length > precision) {
throw new Error(
`Amount ${amountStr} exceeds allowed precision ${precision}`
)
}
const paddedFrac = fracPart.padEnd(precision, "0")
const normalized = intPart + paddedFrac
const paddedFrac = fracTrimmed.padEnd(precision, "0")
const combined = intPart + paddedFrac
return BigInt(normalized)
const value = BigInt(combined)
return negative ? -value : value
}
export function formatAmountFromInt(value: bigint, precision: number): string {