Skip to content

Commit 12b69e1

Browse files
feat(formula): rmbUpper(amount) writes an amount in Chinese capital numerals (人民币大写) for printed quotes and invoices (#34433)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XD1C1qPMRfafpYhtS1pHdu4)_ Fixes #34332 Clause-②: yes (widening) Metadata-protocol: added Skills-docs: updated here — `skills/objectstack-formula/SKILL.md` lists `rmbUpper(x)` in the stdlib Numbers table (pinned by `skill-catalog-sync.test.ts`), and `content/docs/data-modeling/formulas.mdx` adds the catalog row and an "Amount in Chinese capitals" cookbook entry. ## 维护者速读 - **改了什么**:公式标准库新增 `rmbUpper(金额)`,把金额写成人民币大写,如 `245000` → `贰拾肆万伍仟元整`、`10500.5` → `壹万零伍佰元伍角`;报价单、合同、发票的打印页用一个公式字段就能显示「大写金额」。 - **为什么改**:中文商务单据都要在数字下面再印一行大写金额,平台原来没有这个函数,应用自己用 CEL 写既长又容易在「零」、万/亿、角分规则上出错;本卡由你升为 p1(记录 6918041400)。 - **风险与回滚**:只新增一个函数,已有公式的取值都不变;回滚即撤掉本 PR。金额按精确小数四舍五入到分(`1.005` → `壹元零壹分`),空值显示空,非数字或 10^16 元以上报运行时错误,不会印出错的金额。 - **先看**:`packages/formula/src/rmb-upper.ts`(零与万/亿规则、取整)→ `packages/formula/src/stdlib-rmb-upper.test.ts`(期望值表)→ `skills/objectstack-formula/SKILL.md`(新增一行,删掉一句面向平台开发者的旧建议来付 token 预算)。 - **两分钟验证**:`pnpm --filter @objectstack/formula exec vitest run src/stdlib-rmb-upper.test.ts`,预期全部通过,表中可见 `245000` → `贰拾肆万伍仟元整`。 - **需要你做的**:本 PR 碰受管面 `skills/**`,契约审核(contract review owed)PASS 后由席位请你批准,在此之前无需动作。 ## What changes - **`rmbUpper(dyn): string`** (`packages/formula/src/rmb-upper.ts`, registered in `registerBoundStdLib` beside the other number helpers). An amount as Chinese capital numerals: - digits 零壹贰叁肆伍陆柒捌玖, places 拾佰仟, groups 万 and 亿; a ten is `壹拾`; - one `零` per run of zeros inside the number, none at the end of a group or of the yuan part (`1005` → `壹仟零伍元整`, `10500` → `壹万零伍佰元整`, `100000001` → `壹亿零壹元整`, `1000000` → `壹佰万元整`); a full low group takes no `零` (`107000` → `壹拾万柒仟元整`); - above 亿 the count of 亿 is written with 万 (`10000100000000` → `壹拾万零壹亿元整`); 10^16 yuan and above is refused rather than written as 亿亿; - a whole amount ends in `整`; 角 with no 分 ends at the 角 (`伍角`, as on the card); 分 with no 角 writes `零` for the 角 (`壹元零伍分`); under one yuan is 角 and 分 alone (`0.5` → `伍角`); - `0` → `零元整`, a negative is prefixed `负` (one that rounds to zero is `零元整`), `null` → `''`. - **Rounding** reads the value's own spelling and rounds with the home-amount arithmetic's `divideToPlaces` (ADR-0144 D5): the exact decimal the value spells, rounded once to 分, half away from zero. A number, a bigint (an int literal) and decimal text (a currency column answered as `"245000.00"`) are read; text that spells no decimal, a boolean, a list or a map throws, which the engine reports as a runtime error. - **Catalog**: `CEL_STDLIB_FUNCTIONS` advertises `rmbUpper`; its docblock tallies move 77 to 78 registered, 42 to 43 bare-callable, 30 to 31 added by `registerStdLib`. `cel-engine.test.ts`'s every-advertised-entry probe gains `rmbUpper(10500.5)`. - **Docs**: the formula skill's Numbers table, `formulas.mdx`'s stdlib table and a cookbook entry. - **Platform checklist**: `api-backend.formula-stdlib-matrix` revision 8 counts 31 functions and adds the `rmbUpper` known answers. ## Why Chinese quotes, contracts, order confirmations and invoices print the total in capital numerals beside the figures, and the stdlib had no function for it. Hand-writing the zero, 万/亿 and 角/分 rules in CEL is long and easy to get wrong, and every app printing a Chinese document would copy it. Grade: maintainer ruling 6918041400 (「按价值挑五张升 p1」). It pairs with #34228 (Chinese print layout, PR #34422), which it does not touch. ## Tests - `packages/formula/src/stdlib-rmb-upper.test.ts`, every row evaluated through `celEngine.evaluate` the way a formula field reads it: the card's amounts; places, groups and 零 (28 rows up to `9999999999999999`); 角/分/整 (10 rows); rounding on the exact decimal (`1.005`, `2.675`, `9.995`, `-1.005`); negatives; int and double literals, decimal text, record arithmetic (`3 × 0.1` rounds to `叁角`), `null`; refusals (text, `¥100`, a boolean, a list, 10^16 with a control one 分 below); authoring (`validateExpression('value', 'rmbUpper(record.total)')` with a currency field has no error or warning, and `inferExpressionType` answers `text`). - Drift pins: `cel-stdlib-drift.test.ts` (catalog equals the bare-callable registrations), `skill-catalog-sync.test.ts` (the skill documents every entry), `cel-engine.test.ts` (every entry resolves). <details><summary>Test readings at head 4fffca7</summary> ```text pnpm --filter @objectstack/formula test && pnpm --filter @objectstack/formula typecheck (under os-verify-lock) Test Files 68 passed (68) Tests 1822 passed (1822) os-verify-lock: VERDICT command-exit 0 ``` Ablation (one, source-resolved: the test imports `./cel-engine` relatively, so no dist is involved), through `scripts/ablation-replace.mjs`: the anchor `return head + (low < 1_000n ? '零' : '') + group(Number(low));` replaced by `return head + group(Number(low));` (anchor 1 to 0, blob `22257fca` to `93e3b5cf`). `stdlib-rmb-upper.test.ts` went red on 10 tests, among them `10500.5 → 壹万零伍佰元伍角`, `10001 → 壹万零壹元整`, `1000100 → 壹佰万零壹佰元整` and `10000100000000 → 壹拾万零壹亿元整`. Restored: the file's blob is `22257fca`, equal to `HEAD:packages/formula/src/rmb-upper.ts`, and `git diff HEAD` is empty. </details> ## Acceptance notes - **Name.** `rmbUpper` is the card's own suggestion and reads beside `upper()`; nothing in the stdlib, spec or ui names a Chinese-numeral function today. A reviewer who prefers another name can veto it here: it is one registration, one catalog entry and the docs rows. - **The optional 零.** The rules allow writing or omitting a `零` where the 元 or 万 place is zero but the next lower place is not (`1680.32` → `壹仟陆佰捌拾元叁角贰分` or `…元零叁角贰分`; `107000` → `壹拾万柒仟` or `壹拾万零柒仟`). This writes the form without it. The `零` the rules require (a group starting with zeros after a higher group, `壹万零伍佰`, and an empty 角 before a 分, `壹元零伍分`) is written. - **`null` reads `''`**, as `trim(null)` and `label()` of an empty field do, so an empty total prints an empty line rather than failing the formula. - **Skill token budget.** `skills/objectstack-formula/SKILL.md` had 7 tokens of headroom. The new row is paid by deleting the sentence "If you need a helper that doesn't exist, prefer adding it to the stdlib (small, pure, dependency-free) over inlining a complex CEL expression." The skill ships to app authors whose `@objectstack/formula` is dist-only (the same section says "there is no `src/` to read"), so that advice addresses platform contributors; `formulas.mdx` keeps its "Add new helpers in `packages/formula/src/stdlib.ts`" note for them. Readings: the file 494 to 492 lines, 5990 to 5988 tokens (ceiling 5997); the bundle's SKILL.md files 4594 to 4592 lines. - **Not measured:** no live REST read of a formula field calling `rmbUpper` (the checklist item's live leg); every row runs through the same `celEngine.evaluate` the read path calls. ## Verification <details><summary>Local gates at head 4fffca7 (base 9e6fee1)</summary> - Build closure: `pnpm --filter '@objectstack/formula^...' build`, then `turbo run build --filter=@objectstack/lint... --filter=@objectstack/client-react...` (exit 0) for the gates that read dist. - `node scripts/pm/dispatch-gates.mjs --commands` derived 107 families; all 107 ran (`--ran` reconciliation: 107 derived, 107 run, 0 unrun). 104 exited 0. - `node scripts/check-plugin-teardown-shape.mjs --self-test` exited 3 on the shallow clone (its pinned fixture commit was absent); after `git fetch --depth=1 origin 621a487` it exits 0 (48 cases pass). - `pnpm check:dual-build-cjs-loads`: NOT MEASURED, reason: exit 3 `PREREQUISITE NOT MET`, it reads every package's dist and only the lint and client-react closures were built. CI's run is the reading. - `pnpm check:platform-checklist` exits 1 on one problem that is **not this diff's**: `approvals.json · approvals.approver-resolution-matrix: VARIANTS STALE — ApproverType … now has 11 members but this item's variants were authored against 10`. It exits 1 with the same problem on `origin/main` 9e6fee1 itself (the shared checkout, untouched by this branch); `ApproverType` last changed in 27c0b20 (#34300). This diff edits only the formula stdlib item, which the gate does not flag. Reported to the seat; not fixed here (out of scope). - `node scripts/check-platform-checklist.mjs --changed-from origin/main`: OK, 2 anchored files, 0 lost. - `node scripts/check-skills-token-ratchet.mjs`: exit 0, `skills/objectstack-formula/SKILL.md` 5988 / 5997. - Not run locally (CI's): `test:repo`, repo-wide `pnpm lint`. No dogfood battery is owed (no `!` in the title, no narrowing arm). </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (no `packages/spec` change) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (repo-wide lint is CI's run) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (not touched) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5nHvfaZE5NLUTcWkFZ --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5nHvfaZE5NLUTcWkFZ)_ <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5pmEYLVFDcQ1Z1CS8H --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3e49033 commit 12b69e1

9 files changed

Lines changed: 485 additions & 21 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@objectstack/formula': minor
3+
'@objectstack/skills': patch
4+
---
5+
6+
feat(formula): `rmbUpper(amount)` writes an amount in Chinese capital numerals (人民币大写) for printed quotes, contracts and invoices
7+
8+
Clause-②: yes (widening) — a new CEL stdlib function, `rmbUpper(dyn): string`, registered by `registerStdLib` and advertised in `CEL_STDLIB_FUNCTIONS`; an expression that calls it was refused as an unknown function before, and nothing that worked before is refused or changes value.
9+
Metadata-protocol: added — a formula, predicate or flow value may now call `rmbUpper(...)`.
10+
Skills-docs: updated here — `skills/objectstack-formula/SKILL.md` lists it in the stdlib Numbers table, and `content/docs/data-modeling/formulas.mdx` adds the catalog row and an "Amount in Chinese capitals" cookbook entry.
11+
12+
`rmbUpper(245000)` is `贰拾肆万伍仟元整` and `rmbUpper(10500.5)` is `壹万零伍佰元伍角`. A formula field reads it as text:
13+
14+
```ts
15+
Field.formula({ label: '大写金额', returnType: 'text', expression: 'rmbUpper(record.total_amount)' })
16+
```
17+
18+
- The amount is rounded once to 分, half away from zero, on the exact decimal it spells, so `1.005` is `壹元零壹分` and binary floating point never decides a cent.
19+
- One `零` stands for each run of zeros (`壹仟零伍元整`, `壹万零伍佰元整`, `壹亿零壹元整`), a ten is `壹拾`, the 万 and 亿 groups follow the usual rules, and the count of 亿 above 亿 is written with 万 (`壹拾万零壹亿元整`).
20+
- A whole amount ends in `整`; a 分 with no 角 writes `零` for the 角 (`壹元零伍分`); an amount under one yuan is its 角 and 分 alone (`伍角`).
21+
- `0` is `零元整`, a negative amount is prefixed `负`, and `null` reads `''`, so an empty total prints an empty line.
22+
- A number, a currency field and decimal text (`'245000.00'`) are read. Text that spells no number, a boolean or a list, and an amount of 10^16 yuan or more, is a runtime error rather than some text.

‎content/docs/data-modeling/formulas.mdx‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,7 @@ All functions are pure given a pinned `now`, which is what makes
206206
| `abs(x)` / `round(x)` | number | Numeric helpers |
207207
| `floor(x)` / `ceil(x)` | number | Round toward −∞ / +∞ (`floor(-1.2) == -2`) — **not** integer-division's round-toward-zero |
208208
| `min(a, b)` / `max(a, b)` | dyn | Smaller / larger operand (numeric comparison) |
209+
| `rmbUpper(x)` | string | An amount in Chinese capital numerals (人民币大写), rounded to 分: `rmbUpper(10500.5)` is `壹万零伍佰元伍角` — see [Amount in Chinese capitals](#amount-in-chinese-capitals) |
209210
| `label(record.f)` | string | A select field's option label in the reader's locale — see [Record name from an option label](#record-name-from-an-option-label) |
210211

211212
Add new helpers in
@@ -595,6 +596,37 @@ Field.formula({
595596
})
596597
```
597598

599+
### Amount in Chinese capitals
600+
601+
A Chinese quote, contract or invoice prints its total a second time in capital
602+
numerals (大写金额), under the figures. `rmbUpper()` writes that line:
603+
604+
```typescript
605+
Field.formula({
606+
label: '大写金额',
607+
returnType: 'text',
608+
expression: 'rmbUpper(record.total_amount)',
609+
})
610+
```
611+
612+
| `total_amount` | `rmbUpper(record.total_amount)` |
613+
|:---|:---|
614+
| `245000` | `贰拾肆万伍仟元整` |
615+
| `10500.5` | `壹万零伍佰元伍角` |
616+
| `1.05` | `壹元零伍分` |
617+
| `100000001` | `壹亿零壹元整` |
618+
| `0` | `零元整` |
619+
| `-1200` | `负壹仟贰佰元整` |
620+
| `null` | `''` |
621+
622+
The amount is rounded once to 分, half away from zero, on the decimal it spells
623+
(`1.005` is `壹元零壹分`), so binary floating point never decides a cent. One `零`
624+
stands for each run of zeros, a ten is `壹拾`, a whole amount ends in `整` and an
625+
amount under one yuan is its 角 and 分 alone (`0.5` is `伍角`). A number, a
626+
currency field and decimal text (`'245000.00'`) are read; any other value, and
627+
an amount of 10^16 yuan or more, is a runtime error rather than some text; a
628+
formula field reads that error as `null`.
629+
598630
### Text Manipulation
599631

600632
```typescript

‎docs/qa/platform-checklist/areas/api-backend.json‎

Lines changed: 11 additions & 10 deletions
Large diffs are not rendered by default.

‎packages/formula/src/cel-engine.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -505,7 +505,7 @@ describe('celEngine', () => {
505505
datetime: 'datetime("2026-03-15T08:00:00Z")', isoDate: 'isoDate(today())',
506506
isoDatetime: 'isoDatetime(now())', abs: 'abs(-3.5)', round: 'round(2.6)',
507507
floor: 'floor(6.7)', ceil: 'ceil(6.1)',
508-
min: 'min(1, 2)', max: 'max(1, 2)', upper: 'upper("hi")', lower: 'lower("HI")',
508+
min: 'min(1, 2)', max: 'max(1, 2)', rmbUpper: 'rmbUpper(10500.5)', upper: 'upper("hi")', lower: 'lower("HI")',
509509
trim: 'trim(" x ")', contains: 'contains("hello", "ell")', startsWith: 'startsWith("hi", "h")',
510510
endsWith: 'endsWith("hi", "i")', matches: 'matches("a1", "a.")', joinNonEmpty: 'joinNonEmpty(["a", "b"], "-")',
511511
isBlank: 'isBlank("")', isEmpty: 'isEmpty([])', coalesce: 'coalesce(null, "x")', len: 'len("ab")',

‎packages/formula/src/rmb-upper.ts‎

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* `rmbUpper(amount)` — an amount of money as Chinese capital numerals
5+
* (人民币大写金额), the line a Chinese quote, contract, order confirmation or
6+
* invoice prints beside the figures: `245000` → `贰拾肆万伍仟元整`,
7+
* `10500.5` → `壹万零伍佰元伍角`.
8+
*
9+
* The rules are the ones bank and accounting documents follow:
10+
*
11+
* - Digits 零壹贰叁肆伍陆柒捌玖, places 拾佰仟 inside a group of four, groups
12+
* 万 and 亿. A ten is written `壹拾` (`10` → `壹拾元整`), never a bare `拾`.
13+
* - One `零` stands for any run of zeros inside the number, and none is
14+
* written at the end of a group or of the yuan part: `1005` → `壹仟零伍`,
15+
* `10500` → `壹万零伍佰`, `100000001` → `壹亿零壹`, `1000000` → `壹佰万`.
16+
* A group of four that starts with zeros after a higher group takes a `零`
17+
* (`壹万零伍佰`); a full group does not (`壹拾万柒仟`, the form the rules
18+
* allow without the optional `零`).
19+
* - Above 亿 the count of 亿 is itself written with 万: `10_0001_0000_0000`
20+
* → `壹拾万零壹亿`. Amounts are refused from 10^16 (一亿亿) up.
21+
* - The yuan part ends in `元`; with no 角 and no 分 the text ends in `整`.
22+
* A 角 with no 分 ends at the 角 (`伍角`). A 分 with no 角 after a yuan part
23+
* writes `零` for the empty 角 (`壹元零伍分`). An amount under one yuan is
24+
* its 角 and 分 alone (`0.5` → `伍角`, `0.05` → `伍分`).
25+
* - Zero is `零元整`. A negative amount is prefixed `负`; one that rounds to
26+
* zero is `零元整`, never `负零元整`.
27+
*
28+
* The amount is rounded to 分 (two decimals) once, half away from zero, on
29+
* the exact decimal it spells — the rounding the home-amount projection uses
30+
* (`divideToPlaces`, `home-amount-arithmetic.ts`), so `1.005` is `壹元零壹分`
31+
* and binary floating point never decides a cent. A number, a bigint or the
32+
* decimal text a driver answers a currency column with (`"245000.00"`, an
33+
* exponent spelling too) is read; `null` reads `''`, the way `trim(null)` and
34+
* `label()` of an empty field do, so an empty total prints an empty line.
35+
* Anything else — text that spells no decimal, a boolean, a list, NaN, an
36+
* infinity — is refused with a throw, which the engine reports as a runtime
37+
* error, rather than printed as some amount.
38+
*
39+
* The spelling is judged before any conversion ({@link spelledFen}): its
40+
* magnitude is read off its digits and exponent, an amount of 10^16 yuan or
41+
* more is refused there (and again after rounding, which can carry
42+
* 9999999999999999.995 up to 10^16), an amount below 0.001 is zero there, and only the
43+
* digits down to the 0.001 place — the place half-away-from-zero rounding to
44+
* 分 reads — are converted. So the work is bounded by the length of the text,
45+
* whatever its exponent says.
46+
*
47+
* Package-internal (NOT re-exported from `index.ts`): the CEL function is the
48+
* published surface.
49+
*/
50+
51+
import { divideToPlaces } from './home-amount-arithmetic';
52+
53+
const DIGITS = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'] as const;
54+
const PLACES = ['', '拾', '佰', '仟'] as const;
55+
56+
const TEN_THOUSAND = 10_000n;
57+
const HUNDRED_MILLION = 100_000_000n;
58+
59+
/** The decimal spellings read: sign, integer digits, fraction digits, exponent. */
60+
const DECIMAL_SPELLING = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/;
61+
62+
/**
63+
* The power of ten of the highest place an amount may reach: 10^15, so the
64+
* largest amount written is 9999万9999亿9999万9999 yuan and 99 分, and 10^16
65+
* (一亿亿, which the 万/亿 scheme would have to write as 亿亿) is refused.
66+
*/
67+
const TOP_PLACE = 15;
68+
69+
/** 10^16 yuan in 分: the smallest amount refused once rounded. */
70+
const LIMIT_FEN = 10n ** 18n;
71+
72+
/** The lowest place rounding to 分 reads: 0.001. */
73+
const BOTTOM_PLACE = -3;
74+
75+
const TOO_LARGE =
76+
'rmbUpper(amount): `amount` is too large to write in capital numerals (10^16 yuan or more).';
77+
78+
/** `n` in 1..9999 with places, one `零` per inner run of zeros and none at the end. */
79+
function group(n: number): string {
80+
let text = '';
81+
let pendingZero = false;
82+
for (let place = 3; place >= 0; place--) {
83+
const digit = Math.floor(n / 10 ** place) % 10;
84+
if (digit === 0) {
85+
if (text !== '') pendingZero = true;
86+
continue;
87+
}
88+
if (pendingZero) {
89+
text += '零';
90+
pendingZero = false;
91+
}
92+
text += DIGITS[digit] + PLACES[place];
93+
}
94+
return text;
95+
}
96+
97+
/** A positive whole number of yuan, below 10^16. */
98+
function yuan(n: bigint): string {
99+
if (n < TEN_THOUSAND) return group(Number(n));
100+
if (n < HUNDRED_MILLION) {
101+
const low = n % TEN_THOUSAND;
102+
const head = group(Number(n / TEN_THOUSAND)) + '万';
103+
if (low === 0n) return head;
104+
return head + (low < 1_000n ? '零' : '') + group(Number(low));
105+
}
106+
const low = n % HUNDRED_MILLION;
107+
const head = yuan(n / HUNDRED_MILLION) + '亿';
108+
if (low === 0n) return head;
109+
return head + (low < 10_000_000n ? '零' : '') + yuan(low);
110+
}
111+
112+
/** The capital-numeral text of `amount`, rounded to 分; see the module docblock. */
113+
export function rmbUpper(amount: unknown): string {
114+
if (amount === null || amount === undefined) return '';
115+
const fen = spelledFen(amount);
116+
const negative = fen < 0n;
117+
const abs = negative ? -fen : fen;
118+
if (abs === 0n) return '零元整';
119+
120+
const whole = abs / 100n;
121+
const jiao = Number((abs / 10n) % 10n);
122+
const fenDigit = Number(abs % 10n);
123+
124+
let text = whole > 0n ? yuan(whole) + '元' : '';
125+
if (jiao === 0 && fenDigit === 0) {
126+
text += '整';
127+
} else {
128+
if (jiao > 0) text += DIGITS[jiao] + '角';
129+
else if (whole > 0n) text += '零';
130+
if (fenDigit > 0) text += DIGITS[fenDigit] + '分';
131+
}
132+
return (negative ? '负' : '') + text;
133+
}
134+
135+
/**
136+
* `amount` in 分, rounded half away from zero, with the magnitude judged from
137+
* the spelling before anything is converted: 10^16 yuan or more throws, an
138+
* amount below 0.001 is 0, and only the digits from the leading one down to
139+
* the 0.001 place become a number — the digits below it cannot move the
140+
* rounding, because half away from zero at 分 reads the 0.001 digit alone.
141+
*/
142+
function spelledFen(amount: unknown): bigint {
143+
let text: string | undefined;
144+
if (typeof amount === 'number') text = Number.isFinite(amount) ? String(amount) : undefined;
145+
else if (typeof amount === 'bigint') text = amount.toString();
146+
else if (typeof amount === 'string') text = amount.trim();
147+
const m = text === undefined ? null : DECIMAL_SPELLING.exec(text);
148+
if (!m || (m[2] === '' && (m[3] ?? '') === '')) {
149+
throw new Error(
150+
`rmbUpper(amount): \`amount\` is not a number (${describe(amount)}). ` +
151+
'Pass a number, a currency field, or decimal text such as "245000.00".',
152+
);
153+
}
154+
const [, sign, int, frac = '', exp] = m;
155+
const digits = int + frac;
156+
const lead = digits.search(/[1-9]/);
157+
if (lead === -1) return 0n;
158+
// The power of ten of the leading digit; a long exponent reads ±Infinity.
159+
const place = int.length - 1 - lead + (exp === undefined ? 0 : Number(exp));
160+
if (place > TOP_PLACE) throw new Error(TOO_LARGE);
161+
if (place < BOTTOM_PLACE) return 0n;
162+
const kept = digits.slice(lead, lead + place - BOTTOM_PLACE + 1).padEnd(place - BOTTOM_PLACE + 1, '0');
163+
const thousandths = BigInt(sign === '-' ? `-${kept}` : kept);
164+
const fen = divideToPlaces({ digits: thousandths, scale: -BOTTOM_PLACE }, { digits: 1n, scale: 0 }, 2).digits;
165+
// Rounding can carry an amount at the top place up to 10^16 itself
166+
// (9999999999999999.995 → 10^16): refused like any other amount that large.
167+
if ((fen < 0n ? -fen : fen) >= LIMIT_FEN) throw new Error(TOO_LARGE);
168+
return fen;
169+
}
170+
171+
/** A short, value-free description of a refused argument for the error text. */
172+
function describe(value: unknown): string {
173+
if (typeof value === 'string') return 'text that spells no decimal';
174+
if (typeof value === 'number') return Number.isNaN(value) ? 'NaN' : 'an infinite number';
175+
if (Array.isArray(value)) return 'a list';
176+
return typeof value === 'object' ? 'a map' : `a ${typeof value}`;
177+
}

0 commit comments

Comments
 (0)