tiny-ja-money 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/API.md +131 -0
- package/CHANGELOG.md +19 -0
- package/LICENSE +21 -0
- package/README.ja.md +107 -0
- package/README.md +105 -2
- package/dist/amount.d.ts +5 -0
- package/dist/amount.js +20 -0
- package/dist/calculate.d.ts +18 -0
- package/dist/calculate.js +76 -0
- package/dist/distribute.d.ts +7 -0
- package/dist/distribute.js +61 -0
- package/dist/format.d.ts +14 -0
- package/dist/format.js +57 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +5 -0
- package/dist/numerals.d.ts +4 -0
- package/dist/numerals.js +12 -0
- package/dist/parse.d.ts +16 -0
- package/dist/parse.js +115 -0
- package/package.json +29 -4
package/API.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# API reference
|
|
2
|
+
|
|
3
|
+
All functions and types are named exports from `tiny-ja-money`. Amounts are expressed in whole yen.
|
|
4
|
+
|
|
5
|
+
## Amount types
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
type YenAmount = bigint | number
|
|
9
|
+
type YenInput = YenAmount | string
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
A `number` must be a finite safe integer within `±9,007,199,254,740,991`. It is converted exactly to `bigint` before arithmetic. A fractional or non-finite `number` raises `TypeError`. An integer `number` beyond that range raises `RangeError`. Pass a `bigint` or use `parseYen` with a string for larger amounts. Parsing, arithmetic, and decimal formatting support the magnitude range of the runtime's `BigInt` implementation.
|
|
13
|
+
|
|
14
|
+
`toSafeYenNumber(value: YenAmount): number` converts an amount to a safe integer. It raises `RangeError` if the output would be outside the safe range. Native BigInt values can be serialized as decimal strings with `.toString()`.
|
|
15
|
+
|
|
16
|
+
## Parsing
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
interface ParseYenOptions {
|
|
20
|
+
trim?: boolean
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type ParseYenFailureReason = "empty" | "invalid_type" | "invalid_number" | "unsafe_integer" | "invalid_format"
|
|
24
|
+
type ParseYenResult = { ok: true; value: bigint } | { ok: false; reason: ParseYenFailureReason }
|
|
25
|
+
|
|
26
|
+
function parseYen(value: YenInput, options?: ParseYenOptions): bigint
|
|
27
|
+
function tryParseYen(value: unknown, options?: ParseYenOptions): ParseYenResult
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The grammar below applies after converting supported fullwidth characters and U+2212 (`−`) to their ordinary equivalents. `trim` defaults to `false`. Set it to `true` to apply `String.prototype.trim()` before parsing.
|
|
31
|
+
|
|
32
|
+
| Component | Accepted forms |
|
|
33
|
+
| --- | --- |
|
|
34
|
+
| Sign | Optional `+`, `-`, `−`, `+`, `-`, or `マイナス` before the whole amount. One enclosing pair of `()` or `()` denotes a negative amount and replaces the sign. Zero always parses to `0n`. |
|
|
35
|
+
| Currency | Optional `¥` or `¥` prefix, or `円` suffix. Each amount may carry one currency marker. |
|
|
36
|
+
| Positional digits | `0`–`9` and their fullwidth equivalents can mix in a digit run. A separate kanji digit run uses `〇零一二三四五六七八九`, with either zero glyph accepted. Unseparated Arabic and kanji digits form separate grammars, so `1二` is invalid. Ungrouped whole numerals permit leading zeros. |
|
|
37
|
+
| Commas | An Arabic integer can use comma groups of exactly three digits after the first one-to-three-digit group. The first group starts with a nonzero digit. Fullwidth `,` is accepted. Commas are valid only in a positional Arabic amount. |
|
|
38
|
+
| Large units | `兆`, `億`, `万` appear at most once each in descending order. Each unit has an explicit coefficient from 1 to 9,999. The optional trailing group is also from 1 to 9,999. Standalone `万` and `1億10000万` fail. |
|
|
39
|
+
| Small units | Inside a group, `千`, `百`, `十` appear at most once each in descending order. Each coefficient is one nonzero digit, or omitted for one. The optional positional tail must fit below the last unit. Positional segments inside groups with units start with a nonzero digit. `3千430`, `一万2千三百45`, and `三万五千` are valid. |
|
|
40
|
+
|
|
41
|
+
Interior whitespace, fractions of a yen, scientific notation, daiji (`壱`, `萬`), and units `京` and above are outside the grammar.
|
|
42
|
+
|
|
43
|
+
| `tryParseYen` failure | Meaning | `parseYen` error |
|
|
44
|
+
| --- | --- | --- |
|
|
45
|
+
| `empty` | The string is empty after optional trimming. | `TypeError` |
|
|
46
|
+
| `invalid_type` | The input is outside `YenInput`. | `TypeError` |
|
|
47
|
+
| `invalid_number` | The input is a fractional or non-finite `number`. | `TypeError` |
|
|
48
|
+
| `unsafe_integer` | The input is an integer `number` outside the safe range. | `RangeError` |
|
|
49
|
+
| `invalid_format` | The string violates the grammar. | `TypeError` |
|
|
50
|
+
|
|
51
|
+
## Formatting
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
interface YenDisplayOptions {
|
|
55
|
+
currency?: "円" | "¥" | "¥" | "none"
|
|
56
|
+
negative?: "minus" | "parentheses"
|
|
57
|
+
zero?: "0" | "〇" | "零"
|
|
58
|
+
}
|
|
59
|
+
interface FormatYenOptions extends YenDisplayOptions {
|
|
60
|
+
grouping?: boolean
|
|
61
|
+
}
|
|
62
|
+
interface FormatJapaneseAmountOptions extends YenDisplayOptions {
|
|
63
|
+
digits?: "arabic" | "kanji"
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function formatYen(value: YenAmount, options?: FormatYenOptions): string
|
|
67
|
+
function formatJapaneseAmount(value: YenAmount, options?: FormatJapaneseAmountOptions): string
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`formatYen` uses halfwidth digits, groups thousands with `,` by default, and appends `円`. `grouping: false` removes commas. Use `currency` to choose the suffix, either prefix symbol, or no marker. The default negative form starts with `-`. `negative: "parentheses"` wraps the complete label. `zero` defaults to `"0"` for Arabic output and `"〇"` for kanji output.
|
|
71
|
+
|
|
72
|
+
`formatJapaneseAmount` produces exact groups in descending order through `兆` and omits zero groups. It defaults to Arabic digits, for example `1億2500万円`. Kanji uses `千`, `百`, `十` within each group, for example `一億二千五百万円`. Magnitudes of `10^16` yen or more raise `RangeError`. Use `formatYen` for exact decimal formatting at those magnitudes. Both functions round-trip through strict `parseYen` over their documented ranges.
|
|
73
|
+
|
|
74
|
+
`Intl.NumberFormat` is suitable for locale-aware presentation. This API fixes the exact grouping positions, signs, and currency glyphs as part of the parseable format. ECMAScript leaves some of those presentation choices to the `Intl` implementation, so the formatters use fixed string rules. [ECMA-402 NumberFormat](https://tc39.es/ecma402/#sec-intl-numberformat-internal-slots)
|
|
75
|
+
|
|
76
|
+
## Arithmetic, tax, and discounts
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
type Rate = string | { numerator: YenAmount; denominator: YenAmount }
|
|
80
|
+
type RoundingMode = "floor" | "ceil" | "trunc" | "half-up" | "half-even"
|
|
81
|
+
interface RoundingOptions {
|
|
82
|
+
rounding: RoundingMode
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
A rate string uses an optional ASCII sign, one or more ASCII digits, and an optional decimal point followed by one or more digits. `"0.10"` and `{ numerator: 1, denominator: 10n }` are exact equivalents. Fraction denominators must be strictly positive. Rates, products, division, and rounding comparisons use BigInt arithmetic. Wrong types, malformed rate strings, and absent or invalid rounding modes raise `TypeError`. Out-of-range rates and nonpositive denominators raise `RangeError`.
|
|
87
|
+
|
|
88
|
+
| Function | Formula and behavior |
|
|
89
|
+
| --- | --- |
|
|
90
|
+
| `addYen(left, right)` | `left + right`. |
|
|
91
|
+
| `subtractYen(left, right)` | `left - right`. Use for a fixed yen discount. |
|
|
92
|
+
| `multiplyYen(value, rate, options)` | `round(value × rate)`. Signed rates are allowed. |
|
|
93
|
+
| `calculateTax(net, rate, options)` | `round(net × rate)`. |
|
|
94
|
+
| `calculateTaxInclusive(net, rate, options)` | `net + round(net × rate)`. |
|
|
95
|
+
| `calculateIncludedTax(gross, rate, options)` | `round(gross × rate / (1 + rate))`. |
|
|
96
|
+
| `calculateTaxExclusive(gross, rate, options)` | `gross - calculateIncludedTax(gross, rate, options)`. |
|
|
97
|
+
| `applyDiscount(value, rate, options)` | `value - round(value × rate)`. The rate must be between `0` and `1` inclusive. |
|
|
98
|
+
|
|
99
|
+
All listed functions return `bigint`. Amount arguments are `YenAmount`. Tax rates must be nonnegative. A tax conversion rounds the tax component once so tax plus net always equals gross. For example, with `"0.1"` and `floor`, the tax included in `1101n` is `100n` and the derived net is `1001n`. Applying the same policy to that net yields a gross of `1101n`. Other inputs and modes can lose information in the first rounding step, so reversing a conversion can give a different value. Applications choose rates and rounding for each transaction and decide when to aggregate amounts.
|
|
100
|
+
|
|
101
|
+
At a rate of `"0.1"` with `floor`, a gross amount of `10n` contains `0n` of tax and yields a net amount of `10n`. Computing the gross from that net with the same policy gives `11n`. When the gross is the input, keep that amount alongside the net and included tax so the breakdown adds up to the original total.
|
|
102
|
+
|
|
103
|
+
| Mode | Rule | `2.5` | `-2.5` | `-1.5` |
|
|
104
|
+
| --- | --- | ---: | ---: | ---: |
|
|
105
|
+
| `floor` | Toward negative infinity | `2` | `-3` | `-2` |
|
|
106
|
+
| `ceil` | Toward positive infinity | `3` | `-2` | `-1` |
|
|
107
|
+
| `trunc` | Toward zero | `2` | `-2` | `-1` |
|
|
108
|
+
| `half-up` | Nearest integer, ties away from zero | `3` | `-3` | `-2` |
|
|
109
|
+
| `half-even` | Nearest integer, ties to the even one | `2` | `-2` | `-2` |
|
|
110
|
+
|
|
111
|
+
## Splitting and allocation
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
interface SplitAmountOptions {
|
|
115
|
+
maxCount?: number
|
|
116
|
+
}
|
|
117
|
+
function splitAmount(value: YenAmount, count: number, options?: SplitAmountOptions): bigint[]
|
|
118
|
+
function allocateAmount(value: YenAmount, ratios: readonly YenAmount[]): bigint[]
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
- `splitAmount` requires `count` to be an integer from 1 to 4,294,967,295 and returns that many entries. Set `maxCount` to an integer in the same range to cap the number of entries. An invalid count, an invalid limit, or a count above the limit raises `RangeError` before allocating the array. Omitting `maxCount` uses the full array-length range. Each share differs from the others by at most one yen. Extra yen go to the earliest entries.
|
|
122
|
+
- `allocateAmount` requires a nonempty array of nonnegative integer weights with a positive total. To represent fractional weights, scale them to a common integer denominator. The algorithm assigns the whole-yen portion of each exact quota, distributes leftover yen to the largest fractional remainders, and resolves ties in input order. A zero weight always gets `0n`. Invalid array or weight types raise `TypeError`. Negative weights, unsafe integer weights, or a zero total raise `RangeError`.
|
|
123
|
+
- Both algorithms distribute the magnitude, then restore the original sign. The result sums exactly to the original amount and preserves the input order of recipients.
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
splitAmount(-1000, 3) // [-334n, -333n, -333n]
|
|
127
|
+
splitAmount(1000, 3, { maxCount: 3 }) // [334n, 333n, 333n]
|
|
128
|
+
splitAmount(1000, 4, { maxCount: 3 }) // throws RangeError
|
|
129
|
+
allocateAmount(2, [2, 3, 4]) // [0n, 1n, 1n]
|
|
130
|
+
allocateAmount(-2, [2, 3, 4]) // [0n, -1n, -1n]
|
|
131
|
+
```
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.2 (unreleased)
|
|
4
|
+
|
|
5
|
+
- Added an optional `maxCount` to `splitAmount` to limit the number of entries before allocating the result.
|
|
6
|
+
- Added a tax rounding example that shows how to preserve the original gross amount alongside its net and tax components.
|
|
7
|
+
- Fixed package verification when npm's dry-run setting is inherited and added CI coverage for both settings.
|
|
8
|
+
|
|
9
|
+
## 0.1.1 (unreleased)
|
|
10
|
+
|
|
11
|
+
- Added GitHub and live demo links for `ja-char-check`, `ja-ime-utils`, `ja-input-mask`, and `ja-zengin-utils` to both READMEs and the demo.
|
|
12
|
+
- Linked the public tiny-ja-money demo and API reference and updated the version in the CDN examples.
|
|
13
|
+
|
|
14
|
+
## 0.1.0
|
|
15
|
+
|
|
16
|
+
- Added strict whole-yen parsing with fullwidth characters, Japanese numerals through 兆, and typed failure reasons.
|
|
17
|
+
- Added locale-independent yen, Japanese-unit, and kanji formatting.
|
|
18
|
+
- Added exact BigInt arithmetic, decimal and fraction rates, five rounding modes, tax and discount calculations, and sum-preserving allocations.
|
|
19
|
+
- Added ESM packaging, TypeScript declarations, bilingual READMEs, an API reference, release checks, and a static GitHub Pages demo.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fusai Hanabi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.ja.md
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# tiny-ja-money
|
|
2
|
+
|
|
3
|
+
[English](README.md) · [ライブデモ](https://fusaihanabi.github.io/tiny-ja-money/) · [API リファレンス](API.md) · [関連ライブラリ](#関連ライブラリ) · [変更履歴](CHANGELOG.md)
|
|
4
|
+
|
|
5
|
+
日本円の解析・整形・計算を行う小さな TypeScript ライブラリです。Fusai Hanabi OSS シリーズの [tiny-ja-date](https://github.com/fusaihanabi/tiny-ja-date) の姉妹ライブラリです。
|
|
6
|
+
|
|
7
|
+
## インストール
|
|
8
|
+
|
|
9
|
+
npm 公開後は次のコマンドでインストールできます。
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install tiny-ja-money
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
名前付き ESM エクスポートと TypeScript 型定義を提供します。BigInt をサポートする ES2020 対応ブラウザと Node.js で利用でき、ランタイム依存はありません。
|
|
16
|
+
|
|
17
|
+
ソースから使う場合は、このディレクトリで `npm ci`、`npm run build`、`npm pack` を実行し、生成された `tiny-ja-money-0.1.2.tgz` を利用側のプロジェクトにインストールします。
|
|
18
|
+
|
|
19
|
+
### CDN からブラウザで使う
|
|
20
|
+
|
|
21
|
+
`0.1.2` の npm 公開後は、`<script type="module">` から ESM を直接読み込めます。URL には利用する公開版のバージョンを指定します。
|
|
22
|
+
|
|
23
|
+
```html
|
|
24
|
+
<script type="module">
|
|
25
|
+
import { parseYen, formatYen } from "https://unpkg.com/tiny-ja-money@0.1.2/dist/index.js"
|
|
26
|
+
|
|
27
|
+
console.log(formatYen(parseYen("三万五千円"))) // "35,000円"
|
|
28
|
+
</script>
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
jsDelivr から読み込む場合は `https://cdn.jsdelivr.net/npm/tiny-ja-money@0.1.2/dist/index.js` を指定します。
|
|
32
|
+
|
|
33
|
+
## 使用例
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import {
|
|
37
|
+
allocateAmount,
|
|
38
|
+
calculateTaxExclusive,
|
|
39
|
+
calculateTaxInclusive,
|
|
40
|
+
formatJapaneseAmount,
|
|
41
|
+
formatYen,
|
|
42
|
+
parseYen,
|
|
43
|
+
splitAmount,
|
|
44
|
+
tryParseYen,
|
|
45
|
+
} from "tiny-ja-money"
|
|
46
|
+
|
|
47
|
+
parseYen("¥12,800") // 12800n
|
|
48
|
+
parseYen("三万五千円") // 35000n
|
|
49
|
+
tryParseYen("12,80円") // { ok: false, reason: "invalid_format" }
|
|
50
|
+
formatYen(12800) // "12,800円"
|
|
51
|
+
formatJapaneseAmount(125000000) // "1億2500万円"
|
|
52
|
+
formatJapaneseAmount(125000000n, { digits: "kanji" }) // "一億二千五百万円"
|
|
53
|
+
calculateTaxInclusive(1005, "0.1", { rounding: "floor" }) // 1105n
|
|
54
|
+
calculateTaxExclusive(1101, "0.1", { rounding: "floor" }) // 1001n
|
|
55
|
+
splitAmount(1000, 3, { maxCount: 1000 }) // [334n, 333n, 333n]
|
|
56
|
+
allocateAmount(1000, [1, 2, 3]) // [167n, 333n, 500n]
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## 精度と入力規則
|
|
60
|
+
|
|
61
|
+
- 金額の単位は整数の円です。`bigint` と安全な整数の `number` を受け付け、計算結果は常に `bigint` を返します。安全な整数範囲を超える金額には、文字列を `parseYen` で解析するか `bigint` を直接渡します。`number` に戻す場合は `toSafeYenNumber`、JSON に保存する場合は `.toString()` を使えます。
|
|
62
|
+
- 既定で厳密に解析します。全角数字、円記号、漢数字、単位による表記、負数を扱います。`{ trim: true }` で文字列の前後の空白を許容できます。文法と失敗理由は [解析 API](API.md#parsing) に記載しています。
|
|
63
|
+
- `formatYen` はすべての桁を保持します。`formatJapaneseAmount` は絶対値が `10^16` 円未満の金額を万・億・兆で表します。区切りと記号を固定し、実行環境のロケールによる表記の変化を避けています。
|
|
64
|
+
- 税率・割引率は `"0.1"` のような十進文字列か `{ numerator: 1n, denominator: 10n }` のような整数の分数で指定します。丸め方式の指定は必須です。税額は、渡された率・金額・丸め方式に従って計算します。[端数処理と算式](API.md#arithmetic-tax-and-discounts)
|
|
65
|
+
- 均等分割では先頭から余りを配り、比率按分では余りの大きい順に配ります。同順位は入力順です。負の金額でも配分後の合計は元の金額に一致します。分割数をユーザーから受け取る場合は、`splitAmount` の `maxCount` で上限を指定できます。
|
|
66
|
+
|
|
67
|
+
## ライブデモ
|
|
68
|
+
|
|
69
|
+
[ライブデモ](https://fusaihanabi.github.io/tiny-ja-money/)では、解析、単位表記、税額計算、均等分割を試せます。GitHub Pages の公開元は `/docs` です。ライブラリと同じソースから生成した ESM を読み込みます。
|
|
70
|
+
|
|
71
|
+
手元でデモを起動する場合は、次のコマンドを実行します。
|
|
72
|
+
|
|
73
|
+
```sh
|
|
74
|
+
npm ci
|
|
75
|
+
npm run build:demo
|
|
76
|
+
python -m http.server 8000 --bind 127.0.0.1 --directory docs
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
[ローカルデモ](http://127.0.0.1:8000)を開いてください。`src` を変更したら `docs/lib` を再生成します。
|
|
80
|
+
|
|
81
|
+
## 関連ライブラリ
|
|
82
|
+
|
|
83
|
+
請求書の発行日や支払期限には `tiny-ja-date` を使えます。注文フォームで住所や連絡先も受け付ける場合は、入力の正規化・検証ライブラリと組み合わせられます。
|
|
84
|
+
|
|
85
|
+
| ライブラリ | 用途 | リンク |
|
|
86
|
+
| --- | --- | --- |
|
|
87
|
+
| `tiny-ja-date` | 日本語の日付表示、相対日付、営業日計算 | [GitHub](https://github.com/fusaihanabi/tiny-ja-date) · [ライブデモ](https://fusaihanabi.github.io/tiny-ja-date/) |
|
|
88
|
+
| `normalize-ja-input` | フォーム入力の全角・半角、スペース、ハイフンなどの表記ゆれを正規化 | [GitHub](https://github.com/fusaihanabi/normalize-ja-input) · [ライブデモ](https://fusaihanabi.github.io/normalize-ja-input/) |
|
|
89
|
+
| `ja-form-validators` | 郵便番号・電話番号・フリガナなどの入力を検証 | [GitHub](https://github.com/fusaihanabi/ja-form-validators) · [ライブデモ](https://fusaihanabi.github.io/ja-form-validators/) |
|
|
90
|
+
| `ja-char-check` | CSV や外部システムとの連携時に文字コードの互換性とバイト数を検査 | [GitHub](https://github.com/fusaihanabi/ja-char-check) · [ライブデモ](https://fusaihanabi.github.io/ja-char-check/) |
|
|
91
|
+
| `ja-ime-utils` | IME の変換確定とフォーム送信を区別し、確定後の入力を処理 | [GitHub](https://github.com/fusaihanabi/ja-ime-utils) · [ライブデモ](https://fusaihanabi.github.io/ja-ime-utils/) |
|
|
92
|
+
| `ja-input-mask` | 日本語 IME を考慮して郵便番号・電話番号・日付などを入力欄で整形 | [GitHub](https://github.com/fusaihanabi/ja-input-mask) · [ライブデモ](https://fusaihanabi.github.io/ja-input-mask/) |
|
|
93
|
+
| `ja-zengin-utils` | 全銀カナを扱い、総合振込の120バイト固定長レコードを生成・解析 | [GitHub](https://github.com/fusaihanabi/ja-zengin-utils) · [ライブデモ](https://fusaihanabi.github.io/ja-zengin-utils/) |
|
|
94
|
+
|
|
95
|
+
[Fusai Hanabi OSS 公式サイト](https://dl.fusai-hanabi.com/)
|
|
96
|
+
|
|
97
|
+
## 開発
|
|
98
|
+
|
|
99
|
+
```sh
|
|
100
|
+
npm ci
|
|
101
|
+
npm run typecheck
|
|
102
|
+
npm test
|
|
103
|
+
npm run build
|
|
104
|
+
npm run check:package
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
[MIT ライセンス](LICENSE)で提供します。
|
package/README.md
CHANGED
|
@@ -1,3 +1,106 @@
|
|
|
1
|
-
#
|
|
1
|
+
# tiny-ja-money
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[日本語](README.ja.md) · [Live demo](https://fusaihanabi.github.io/tiny-ja-money/) · [API reference](API.md) · [Related libraries](#related-libraries) · [Changelog](CHANGELOG.md)
|
|
4
|
+
|
|
5
|
+
Tiny TypeScript utilities for parsing, formatting, and calculating whole Japanese yen. Part of the Fusai Hanabi OSS series alongside [tiny-ja-date](https://github.com/fusaihanabi/tiny-ja-date).
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Install from npm once the package is published.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install tiny-ja-money
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The package supplies named ESM exports and TypeScript declarations for BigInt-capable browser and Node.js runtimes. It targets ES2020 and has zero runtime dependencies.
|
|
16
|
+
|
|
17
|
+
To build from source, run `npm ci`, `npm run build`, and `npm pack` in this checkout. Install the resulting `tiny-ja-money-0.1.2.tgz` in the consuming project.
|
|
18
|
+
|
|
19
|
+
### Browser ESM via CDN
|
|
20
|
+
|
|
21
|
+
Once `0.1.2` is on npm, import its ESM entry point from a `<script type="module">`. Pin the published version you want to load.
|
|
22
|
+
|
|
23
|
+
```html
|
|
24
|
+
<script type="module">
|
|
25
|
+
import { parseYen, formatYen } from "https://unpkg.com/tiny-ja-money@0.1.2/dist/index.js"
|
|
26
|
+
|
|
27
|
+
console.log(formatYen(parseYen("三万五千円"))) // "35,000円"
|
|
28
|
+
</script>
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The equivalent jsDelivr URL is `https://cdn.jsdelivr.net/npm/tiny-ja-money@0.1.2/dist/index.js`.
|
|
32
|
+
|
|
33
|
+
## Usage
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import {
|
|
37
|
+
allocateAmount,
|
|
38
|
+
calculateTax,
|
|
39
|
+
calculateTaxInclusive,
|
|
40
|
+
formatJapaneseAmount,
|
|
41
|
+
formatYen,
|
|
42
|
+
parseYen,
|
|
43
|
+
splitAmount,
|
|
44
|
+
tryParseYen,
|
|
45
|
+
} from "tiny-ja-money"
|
|
46
|
+
|
|
47
|
+
parseYen("1億2500万円") // 125000000n
|
|
48
|
+
tryParseYen("12,80円") // { ok: false, reason: "invalid_format" }
|
|
49
|
+
formatYen(12800) // "12,800円"
|
|
50
|
+
formatJapaneseAmount(125000000) // "1億2500万円"
|
|
51
|
+
formatJapaneseAmount(125000000n, { digits: "kanji" }) // "一億二千五百万円"
|
|
52
|
+
calculateTax(1005, "0.1", { rounding: "floor" }) // 100n
|
|
53
|
+
calculateTaxInclusive(1005, "0.1", { rounding: "floor" }) // 1105n
|
|
54
|
+
splitAmount(1000, 3, { maxCount: 1000 }) // [334n, 333n, 333n]
|
|
55
|
+
allocateAmount(1000, [1, 2, 3]) // [167n, 333n, 500n]
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Precision and validation
|
|
59
|
+
|
|
60
|
+
- Amounts are whole yen. Money functions accept `bigint` and safe integer `number` inputs, and calculations return `bigint`. Parse large values from text or supply a `bigint` directly. Use `toSafeYenNumber` for checked conversion to `number` and `.toString()` to store an amount as a JSON string.
|
|
61
|
+
- Parsing is strict by default. It accepts `¥` or `¥` before the numeral or `円` after it, fullwidth digits, kanji numerals, and strictly ordered units through `兆`. Set `{ trim: true }` to allow whitespace around the input. See the [grammar and error table](API.md#parsing).
|
|
62
|
+
- `formatYen` always emits exact digits. `formatJapaneseAmount` supports magnitudes below `10^16` yen. Formatting uses fixed separators and symbols so the result is independent of runtime locale data.
|
|
63
|
+
- Rates are exact decimal strings such as `"0.1"` or fractions such as `{ numerator: 1n, denominator: 10n }`. Callers explicitly supply the rate and rounding policy. Tax functions perform arithmetic for the given amount and policy. The [tax formulas](API.md#arithmetic-tax-and-discounts) describe which component is rounded.
|
|
64
|
+
- Equal splits and weighted allocations preserve the original amount, including negative amounts. Set `maxCount` on `splitAmount` to cap the number of entries when accepting user input. Weighted allocation uses largest remainders with ties resolved in input order.
|
|
65
|
+
|
|
66
|
+
## Live demo
|
|
67
|
+
|
|
68
|
+
Try parsing, Japanese notation, tax calculations, and equal splitting in the [live demo](https://fusaihanabi.github.io/tiny-ja-money/). GitHub Pages serves `/docs`, which contains the ESM modules built from the library source.
|
|
69
|
+
|
|
70
|
+
To serve the demo from your checkout:
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
npm ci
|
|
74
|
+
npm run build:demo
|
|
75
|
+
python -m http.server 8000 --bind 127.0.0.1 --directory docs
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Open [the local demo](http://127.0.0.1:8000). Rebuild `docs/lib` after changing `src`.
|
|
79
|
+
|
|
80
|
+
## Related libraries
|
|
81
|
+
|
|
82
|
+
Use `tiny-ja-date` for invoice dates and business days, and pair `tiny-ja-money` with the form tools when an invoice or checkout also collects contact details.
|
|
83
|
+
|
|
84
|
+
| Library | Use it for | Links |
|
|
85
|
+
| --- | --- | --- |
|
|
86
|
+
| `tiny-ja-date` | Japanese date labels, relative dates, and business-day calculations | [GitHub](https://github.com/fusaihanabi/tiny-ja-date) · [Live demo](https://fusaihanabi.github.io/tiny-ja-date/) |
|
|
87
|
+
| `normalize-ja-input` | Normalizing fullwidth and halfwidth characters, spaces, and hyphens in form fields | [GitHub](https://github.com/fusaihanabi/normalize-ja-input) · [Live demo](https://fusaihanabi.github.io/normalize-ja-input/) |
|
|
88
|
+
| `ja-form-validators` | Validating postal codes, phone numbers, and furigana | [GitHub](https://github.com/fusaihanabi/ja-form-validators) · [Live demo](https://fusaihanabi.github.io/ja-form-validators/) |
|
|
89
|
+
| `ja-char-check` | Checking encoding compatibility and byte counts for CSV exports and system integrations | [GitHub](https://github.com/fusaihanabi/ja-char-check) · [Live demo](https://fusaihanabi.github.io/ja-char-check/) |
|
|
90
|
+
| `ja-ime-utils` | Distinguishing IME composition confirmation from form submission and handling committed input | [GitHub](https://github.com/fusaihanabi/ja-ime-utils) · [Live demo](https://fusaihanabi.github.io/ja-ime-utils/) |
|
|
91
|
+
| `ja-input-mask` | Formatting postal codes, phone numbers, and dates as users type with Japanese IME support | [GitHub](https://github.com/fusaihanabi/ja-input-mask) · [Live demo](https://fusaihanabi.github.io/ja-input-mask/) |
|
|
92
|
+
| `ja-zengin-utils` | Handling Zengin kana and creating or parsing 120-byte fixed-width bulk transfer records | [GitHub](https://github.com/fusaihanabi/ja-zengin-utils) · [Live demo](https://fusaihanabi.github.io/ja-zengin-utils/) |
|
|
93
|
+
|
|
94
|
+
[Fusai Hanabi OSS](https://dl.fusai-hanabi.com/)
|
|
95
|
+
|
|
96
|
+
## Development
|
|
97
|
+
|
|
98
|
+
```sh
|
|
99
|
+
npm ci
|
|
100
|
+
npm run typecheck
|
|
101
|
+
npm test
|
|
102
|
+
npm run build
|
|
103
|
+
npm run check:package
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Released under the [MIT license](LICENSE).
|
package/dist/amount.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** A whole-yen amount. A number must be a safe integer. */
|
|
2
|
+
export type YenAmount = bigint | number;
|
|
3
|
+
export declare function toBigInt(value: YenAmount): bigint;
|
|
4
|
+
export declare function toSafeYenNumber(value: YenAmount): number;
|
|
5
|
+
export declare function abs(value: bigint): bigint;
|
package/dist/amount.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export function toBigInt(value) {
|
|
2
|
+
if (typeof value === "bigint")
|
|
3
|
+
return value;
|
|
4
|
+
if (typeof value !== "number" || !Number.isInteger(value)) {
|
|
5
|
+
throw new TypeError("Expected a whole-yen bigint or integer number");
|
|
6
|
+
}
|
|
7
|
+
if (!Number.isSafeInteger(value))
|
|
8
|
+
throw new RangeError("Use bigint for amounts outside the safe integer range");
|
|
9
|
+
return BigInt(value);
|
|
10
|
+
}
|
|
11
|
+
export function toSafeYenNumber(value) {
|
|
12
|
+
const amount = toBigInt(value);
|
|
13
|
+
const result = Number(amount);
|
|
14
|
+
if (!Number.isSafeInteger(result))
|
|
15
|
+
throw new RangeError("Amount is outside the safe integer range");
|
|
16
|
+
return result;
|
|
17
|
+
}
|
|
18
|
+
export function abs(value) {
|
|
19
|
+
return value < 0n ? -value : value;
|
|
20
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { YenAmount } from "./amount.js";
|
|
2
|
+
/** Use decimal text such as "0.1", or a fraction with a positive denominator. */
|
|
3
|
+
export type Rate = string | {
|
|
4
|
+
numerator: YenAmount;
|
|
5
|
+
denominator: YenAmount;
|
|
6
|
+
};
|
|
7
|
+
export type RoundingMode = "floor" | "ceil" | "trunc" | "half-up" | "half-even";
|
|
8
|
+
export interface RoundingOptions {
|
|
9
|
+
rounding: RoundingMode;
|
|
10
|
+
}
|
|
11
|
+
export declare function addYen(left: YenAmount, right: YenAmount): bigint;
|
|
12
|
+
export declare function subtractYen(left: YenAmount, right: YenAmount): bigint;
|
|
13
|
+
export declare function multiplyYen(value: YenAmount, rate: Rate, options: RoundingOptions): bigint;
|
|
14
|
+
export declare function calculateTax(value: YenAmount, rate: Rate, options: RoundingOptions): bigint;
|
|
15
|
+
export declare function calculateTaxInclusive(value: YenAmount, rate: Rate, options: RoundingOptions): bigint;
|
|
16
|
+
export declare function calculateIncludedTax(value: YenAmount, rate: Rate, options: RoundingOptions): bigint;
|
|
17
|
+
export declare function calculateTaxExclusive(value: YenAmount, rate: Rate, options: RoundingOptions): bigint;
|
|
18
|
+
export declare function applyDiscount(value: YenAmount, rate: Rate, options: RoundingOptions): bigint;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { abs, toBigInt } from "./amount.js";
|
|
2
|
+
export function addYen(left, right) {
|
|
3
|
+
return toBigInt(left) + toBigInt(right);
|
|
4
|
+
}
|
|
5
|
+
export function subtractYen(left, right) {
|
|
6
|
+
return toBigInt(left) - toBigInt(right);
|
|
7
|
+
}
|
|
8
|
+
function readRate(rate) {
|
|
9
|
+
if (typeof rate === "string") {
|
|
10
|
+
if (!/^[+-]?[0-9]+(?:\.[0-9]+)?$/u.test(rate))
|
|
11
|
+
throw new TypeError("Expected an ASCII decimal rate");
|
|
12
|
+
const [integer, fraction = ""] = rate.split(".");
|
|
13
|
+
return [BigInt(integer + fraction), 10n ** BigInt(fraction.length)];
|
|
14
|
+
}
|
|
15
|
+
if (rate === null || typeof rate !== "object")
|
|
16
|
+
throw new TypeError("Expected a decimal string or fraction rate");
|
|
17
|
+
const numerator = toBigInt(rate.numerator);
|
|
18
|
+
const denominator = toBigInt(rate.denominator);
|
|
19
|
+
if (denominator <= 0n)
|
|
20
|
+
throw new RangeError("Rate denominator must be positive");
|
|
21
|
+
return [numerator, denominator];
|
|
22
|
+
}
|
|
23
|
+
function roundDivision(numerator, denominator, options) {
|
|
24
|
+
const quotient = numerator / denominator;
|
|
25
|
+
const remainder = numerator % denominator;
|
|
26
|
+
const step = numerator < 0n ? -1n : 1n;
|
|
27
|
+
switch (options?.rounding) {
|
|
28
|
+
case "floor":
|
|
29
|
+
return remainder < 0n ? quotient - 1n : quotient;
|
|
30
|
+
case "ceil":
|
|
31
|
+
return remainder > 0n ? quotient + 1n : quotient;
|
|
32
|
+
case "trunc":
|
|
33
|
+
return quotient;
|
|
34
|
+
case "half-up":
|
|
35
|
+
return 2n * abs(remainder) >= denominator ? quotient + step : quotient;
|
|
36
|
+
case "half-even": {
|
|
37
|
+
const doubled = 2n * abs(remainder);
|
|
38
|
+
return doubled > denominator || (doubled === denominator && quotient % 2n !== 0n)
|
|
39
|
+
? quotient + step
|
|
40
|
+
: quotient;
|
|
41
|
+
}
|
|
42
|
+
default:
|
|
43
|
+
throw new TypeError("Specify a valid rounding mode");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export function multiplyYen(value, rate, options) {
|
|
47
|
+
const [numerator, denominator] = readRate(rate);
|
|
48
|
+
return roundDivision(toBigInt(value) * numerator, denominator, options);
|
|
49
|
+
}
|
|
50
|
+
function taxAmount(amount, rate, options, included) {
|
|
51
|
+
const [numerator, denominator] = readRate(rate);
|
|
52
|
+
if (numerator < 0n)
|
|
53
|
+
throw new RangeError("Tax rate must be nonnegative");
|
|
54
|
+
return roundDivision(amount * numerator, included ? denominator + numerator : denominator, options);
|
|
55
|
+
}
|
|
56
|
+
export function calculateTax(value, rate, options) {
|
|
57
|
+
return taxAmount(toBigInt(value), rate, options, false);
|
|
58
|
+
}
|
|
59
|
+
export function calculateTaxInclusive(value, rate, options) {
|
|
60
|
+
const net = toBigInt(value);
|
|
61
|
+
return net + taxAmount(net, rate, options, false);
|
|
62
|
+
}
|
|
63
|
+
export function calculateIncludedTax(value, rate, options) {
|
|
64
|
+
return taxAmount(toBigInt(value), rate, options, true);
|
|
65
|
+
}
|
|
66
|
+
export function calculateTaxExclusive(value, rate, options) {
|
|
67
|
+
const gross = toBigInt(value);
|
|
68
|
+
return gross - taxAmount(gross, rate, options, true);
|
|
69
|
+
}
|
|
70
|
+
export function applyDiscount(value, rate, options) {
|
|
71
|
+
const [numerator, denominator] = readRate(rate);
|
|
72
|
+
if (numerator < 0n || numerator > denominator)
|
|
73
|
+
throw new RangeError("Discount rate must be between 0 and 1");
|
|
74
|
+
const amount = toBigInt(value);
|
|
75
|
+
return amount - roundDivision(amount * numerator, denominator, options);
|
|
76
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { YenAmount } from "./amount.js";
|
|
2
|
+
export interface SplitAmountOptions {
|
|
3
|
+
/** Limit the number of entries before allocating the result array. */
|
|
4
|
+
maxCount?: number;
|
|
5
|
+
}
|
|
6
|
+
export declare function splitAmount(value: YenAmount, count: number, options?: SplitAmountOptions): bigint[];
|
|
7
|
+
export declare function allocateAmount(value: YenAmount, ratios: readonly YenAmount[]): bigint[];
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { abs, toBigInt } from "./amount.js";
|
|
2
|
+
const MAX_ARRAY_LENGTH = 4294967295;
|
|
3
|
+
export function splitAmount(value, count, options = {}) {
|
|
4
|
+
if (!Number.isInteger(count) || count < 1 || count > MAX_ARRAY_LENGTH) {
|
|
5
|
+
throw new RangeError("Split count must be a positive array length");
|
|
6
|
+
}
|
|
7
|
+
const { maxCount } = options;
|
|
8
|
+
if (maxCount !== undefined) {
|
|
9
|
+
if (!Number.isInteger(maxCount) || maxCount < 1 || maxCount > MAX_ARRAY_LENGTH) {
|
|
10
|
+
throw new RangeError("Split maxCount must be a positive array length");
|
|
11
|
+
}
|
|
12
|
+
if (count > maxCount)
|
|
13
|
+
throw new RangeError("Split count exceeds maxCount");
|
|
14
|
+
}
|
|
15
|
+
const amount = toBigInt(value);
|
|
16
|
+
const divisor = BigInt(count);
|
|
17
|
+
const share = amount / divisor;
|
|
18
|
+
const remainder = amount % divisor;
|
|
19
|
+
const extraShares = Number(abs(remainder));
|
|
20
|
+
const step = remainder < 0n ? -1n : 1n;
|
|
21
|
+
return Array.from({ length: count }, (_, index) => index < extraShares ? share + step : share);
|
|
22
|
+
}
|
|
23
|
+
export function allocateAmount(value, ratios) {
|
|
24
|
+
const amount = toBigInt(value);
|
|
25
|
+
if (!Array.isArray(ratios))
|
|
26
|
+
throw new TypeError("Expected an array of integer weights");
|
|
27
|
+
const weights = [];
|
|
28
|
+
let totalWeight = 0n;
|
|
29
|
+
for (const ratio of ratios) {
|
|
30
|
+
const weight = toBigInt(ratio);
|
|
31
|
+
if (weight < 0n)
|
|
32
|
+
throw new RangeError("Allocation weights must be nonnegative");
|
|
33
|
+
totalWeight += weight;
|
|
34
|
+
weights.push(weight);
|
|
35
|
+
}
|
|
36
|
+
if (totalWeight === 0n)
|
|
37
|
+
throw new RangeError("Allocation requires a positive total weight");
|
|
38
|
+
const magnitude = abs(amount);
|
|
39
|
+
let remaining = magnitude;
|
|
40
|
+
const remainders = [];
|
|
41
|
+
const shares = weights.map((weight, index) => {
|
|
42
|
+
const weighted = magnitude * weight;
|
|
43
|
+
const share = weighted / totalWeight;
|
|
44
|
+
const remainder = weighted % totalWeight;
|
|
45
|
+
remaining -= share;
|
|
46
|
+
if (remainder !== 0n)
|
|
47
|
+
remainders.push({ index, value: remainder });
|
|
48
|
+
return share;
|
|
49
|
+
});
|
|
50
|
+
if (remaining > 0n) {
|
|
51
|
+
remainders.sort((left, right) => {
|
|
52
|
+
if (left.value === right.value)
|
|
53
|
+
return left.index - right.index;
|
|
54
|
+
return left.value > right.value ? -1 : 1;
|
|
55
|
+
});
|
|
56
|
+
// Each remainder is less than one yen; their sum is the unassigned yen.
|
|
57
|
+
for (let index = 0; index < Number(remaining); index++)
|
|
58
|
+
shares[remainders[index].index]++;
|
|
59
|
+
}
|
|
60
|
+
return amount < 0n ? shares.map((share) => -share) : shares;
|
|
61
|
+
}
|
package/dist/format.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { YenAmount } from "./amount.js";
|
|
2
|
+
export interface YenDisplayOptions {
|
|
3
|
+
currency?: "円" | "¥" | "¥" | "none";
|
|
4
|
+
negative?: "minus" | "parentheses";
|
|
5
|
+
zero?: "0" | "〇" | "零";
|
|
6
|
+
}
|
|
7
|
+
export interface FormatYenOptions extends YenDisplayOptions {
|
|
8
|
+
grouping?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface FormatJapaneseAmountOptions extends YenDisplayOptions {
|
|
11
|
+
digits?: "arabic" | "kanji";
|
|
12
|
+
}
|
|
13
|
+
export declare function formatYen(value: YenAmount, options?: FormatYenOptions): string;
|
|
14
|
+
export declare function formatJapaneseAmount(value: YenAmount, options?: FormatJapaneseAmountOptions): string;
|
package/dist/format.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { abs, toBigInt } from "./amount.js";
|
|
2
|
+
import { JAPANESE_AMOUNT_LIMIT, KANJI_DIGITS, LARGE_UNITS, SMALL_UNITS } from "./numerals.js";
|
|
3
|
+
function decorate(text, amount, options) {
|
|
4
|
+
const currency = options.currency ?? "円";
|
|
5
|
+
if (currency === "円")
|
|
6
|
+
text += currency;
|
|
7
|
+
if (currency === "¥" || currency === "¥")
|
|
8
|
+
text = currency + text;
|
|
9
|
+
if (amount >= 0n)
|
|
10
|
+
return text;
|
|
11
|
+
return options.negative === "parentheses" ? `(${text})` : `-${text}`;
|
|
12
|
+
}
|
|
13
|
+
function groupDigits(digits) {
|
|
14
|
+
const first = digits.length % 3 || 3;
|
|
15
|
+
const groups = [digits.slice(0, first)];
|
|
16
|
+
for (let index = first; index < digits.length; index += 3) {
|
|
17
|
+
groups.push(digits.slice(index, index + 3));
|
|
18
|
+
}
|
|
19
|
+
return groups.join(",");
|
|
20
|
+
}
|
|
21
|
+
export function formatYen(value, options = {}) {
|
|
22
|
+
const amount = toBigInt(value);
|
|
23
|
+
const digits = abs(amount).toString();
|
|
24
|
+
const text = amount === 0n ? (options.zero ?? "0") : options.grouping === false ? digits : groupDigits(digits);
|
|
25
|
+
return decorate(text, amount, options);
|
|
26
|
+
}
|
|
27
|
+
function formatKanjiGroup(value) {
|
|
28
|
+
let text = "";
|
|
29
|
+
for (const [marker, unit] of SMALL_UNITS) {
|
|
30
|
+
const digit = Math.floor(value / unit);
|
|
31
|
+
if (digit > 0)
|
|
32
|
+
text += (digit === 1 ? "" : KANJI_DIGITS[digit]) + marker;
|
|
33
|
+
value %= unit;
|
|
34
|
+
}
|
|
35
|
+
if (value > 0)
|
|
36
|
+
text += KANJI_DIGITS[value];
|
|
37
|
+
return text;
|
|
38
|
+
}
|
|
39
|
+
export function formatJapaneseAmount(value, options = {}) {
|
|
40
|
+
const amount = toBigInt(value);
|
|
41
|
+
let remaining = abs(amount);
|
|
42
|
+
if (remaining >= JAPANESE_AMOUNT_LIMIT)
|
|
43
|
+
throw new RangeError("Japanese unit notation supports magnitudes below 10^16 yen");
|
|
44
|
+
const kanji = options.digits === "kanji";
|
|
45
|
+
if (remaining === 0n)
|
|
46
|
+
return decorate(options.zero ?? (kanji ? "〇" : "0"), amount, options);
|
|
47
|
+
let text = "";
|
|
48
|
+
for (const [marker, unit] of LARGE_UNITS) {
|
|
49
|
+
const group = remaining / unit;
|
|
50
|
+
if (group !== 0n)
|
|
51
|
+
text += (kanji ? formatKanjiGroup(Number(group)) : group.toString()) + marker;
|
|
52
|
+
remaining %= unit;
|
|
53
|
+
}
|
|
54
|
+
if (remaining !== 0n)
|
|
55
|
+
text += kanji ? formatKanjiGroup(Number(remaining)) : remaining.toString();
|
|
56
|
+
return decorate(text, amount, options);
|
|
57
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { toSafeYenNumber } from "./amount.js";
|
|
2
|
+
export type { YenAmount } from "./amount.js";
|
|
3
|
+
export { parseYen, tryParseYen } from "./parse.js";
|
|
4
|
+
export type { ParseYenFailureReason, ParseYenOptions, ParseYenResult, YenInput } from "./parse.js";
|
|
5
|
+
export { formatJapaneseAmount, formatYen } from "./format.js";
|
|
6
|
+
export type { FormatJapaneseAmountOptions, FormatYenOptions, YenDisplayOptions } from "./format.js";
|
|
7
|
+
export { addYen, applyDiscount, calculateIncludedTax, calculateTax, calculateTaxExclusive, calculateTaxInclusive, multiplyYen, subtractYen, } from "./calculate.js";
|
|
8
|
+
export type { Rate, RoundingMode, RoundingOptions } from "./calculate.js";
|
|
9
|
+
export { allocateAmount, splitAmount } from "./distribute.js";
|
|
10
|
+
export type { SplitAmountOptions } from "./distribute.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { toSafeYenNumber } from "./amount.js";
|
|
2
|
+
export { parseYen, tryParseYen } from "./parse.js";
|
|
3
|
+
export { formatJapaneseAmount, formatYen } from "./format.js";
|
|
4
|
+
export { addYen, applyDiscount, calculateIncludedTax, calculateTax, calculateTaxExclusive, calculateTaxInclusive, multiplyYen, subtractYen, } from "./calculate.js";
|
|
5
|
+
export { allocateAmount, splitAmount } from "./distribute.js";
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare const KANJI_DIGITS = "\u3007\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D";
|
|
2
|
+
export declare const LARGE_UNITS: readonly [readonly ["兆", 1000000000000n], readonly ["億", 100000000n], readonly ["万", 10000n]];
|
|
3
|
+
export declare const SMALL_UNITS: readonly [readonly ["千", 1000], readonly ["百", 100], readonly ["十", 10]];
|
|
4
|
+
export declare const JAPANESE_AMOUNT_LIMIT = 10000000000000000n;
|
package/dist/numerals.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export const KANJI_DIGITS = "〇一二三四五六七八九";
|
|
2
|
+
export const LARGE_UNITS = [
|
|
3
|
+
["兆", 1000000000000n],
|
|
4
|
+
["億", 100000000n],
|
|
5
|
+
["万", 10000n],
|
|
6
|
+
];
|
|
7
|
+
export const SMALL_UNITS = [
|
|
8
|
+
["千", 1000],
|
|
9
|
+
["百", 100],
|
|
10
|
+
["十", 10],
|
|
11
|
+
];
|
|
12
|
+
export const JAPANESE_AMOUNT_LIMIT = 10000000000000000n;
|
package/dist/parse.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { YenAmount } from "./amount.js";
|
|
2
|
+
export type YenInput = YenAmount | string;
|
|
3
|
+
export interface ParseYenOptions {
|
|
4
|
+
/** Allow surrounding whitespace as defined by String.prototype.trim. */
|
|
5
|
+
trim?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export type ParseYenFailureReason = "empty" | "invalid_type" | "invalid_number" | "unsafe_integer" | "invalid_format";
|
|
8
|
+
export type ParseYenResult = {
|
|
9
|
+
ok: true;
|
|
10
|
+
value: bigint;
|
|
11
|
+
} | {
|
|
12
|
+
ok: false;
|
|
13
|
+
reason: ParseYenFailureReason;
|
|
14
|
+
};
|
|
15
|
+
export declare function tryParseYen(value: unknown, options?: ParseYenOptions): ParseYenResult;
|
|
16
|
+
export declare function parseYen(value: YenInput, options?: ParseYenOptions): bigint;
|
package/dist/parse.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { JAPANESE_AMOUNT_LIMIT, KANJI_DIGITS, LARGE_UNITS, SMALL_UNITS } from "./numerals.js";
|
|
2
|
+
function normalizeWidth(value) {
|
|
3
|
+
return value.replace(/[0-9+-¥(),−]/gu, (character) => {
|
|
4
|
+
if (character === "¥")
|
|
5
|
+
return "¥";
|
|
6
|
+
if (character === "−")
|
|
7
|
+
return "-";
|
|
8
|
+
return String.fromCharCode(character.charCodeAt(0) - 0xfee0);
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
function positionalDigits(value) {
|
|
12
|
+
if (/^[0-9]+$/u.test(value))
|
|
13
|
+
return value;
|
|
14
|
+
if (!/^[〇零一二三四五六七八九]+$/u.test(value))
|
|
15
|
+
return undefined;
|
|
16
|
+
return value.replace(/./gu, (character) => String(character === "零" ? 0 : KANJI_DIGITS.indexOf(character)));
|
|
17
|
+
}
|
|
18
|
+
// A large-unit coefficient is a single nonzero four-place group. Inside a
|
|
19
|
+
// group, a positional tail must fit below the last explicit small unit.
|
|
20
|
+
function parseGroup(value) {
|
|
21
|
+
let previousUnit = 10000;
|
|
22
|
+
let total = 0;
|
|
23
|
+
let start = 0;
|
|
24
|
+
for (const match of value.matchAll(/[千百十]/gu)) {
|
|
25
|
+
const marker = match.index;
|
|
26
|
+
const unit = SMALL_UNITS.find(([symbol]) => symbol === match[0])[1];
|
|
27
|
+
const token = value.slice(start, marker);
|
|
28
|
+
if (unit >= previousUnit || token.length > 1)
|
|
29
|
+
return undefined;
|
|
30
|
+
const coefficient = token === "" ? "1" : positionalDigits(token);
|
|
31
|
+
if (coefficient === undefined || coefficient === "0")
|
|
32
|
+
return undefined;
|
|
33
|
+
total += Number(coefficient) * unit;
|
|
34
|
+
previousUnit = unit;
|
|
35
|
+
start = marker + 1;
|
|
36
|
+
}
|
|
37
|
+
const tail = value.slice(start);
|
|
38
|
+
if (tail === "")
|
|
39
|
+
return total || undefined;
|
|
40
|
+
if (tail.length > 4)
|
|
41
|
+
return undefined;
|
|
42
|
+
const digits = positionalDigits(tail);
|
|
43
|
+
if (digits === undefined || digits.startsWith("0"))
|
|
44
|
+
return undefined;
|
|
45
|
+
const remainder = Number(digits);
|
|
46
|
+
return remainder < previousUnit ? total + remainder : undefined;
|
|
47
|
+
}
|
|
48
|
+
function parseNumeral(value) {
|
|
49
|
+
if (/^[1-9][0-9]{0,2}(?:,[0-9]{3})+$/u.test(value))
|
|
50
|
+
return BigInt(value.replace(/,/gu, ""));
|
|
51
|
+
const plain = positionalDigits(value);
|
|
52
|
+
if (plain !== undefined)
|
|
53
|
+
return BigInt(plain);
|
|
54
|
+
let previousUnit = JAPANESE_AMOUNT_LIMIT;
|
|
55
|
+
let total = 0n;
|
|
56
|
+
let start = 0;
|
|
57
|
+
for (const match of value.matchAll(/[兆億万]/gu)) {
|
|
58
|
+
const marker = match.index;
|
|
59
|
+
const unit = LARGE_UNITS.find(([symbol]) => symbol === match[0])[1];
|
|
60
|
+
const group = parseGroup(value.slice(start, marker));
|
|
61
|
+
if (unit >= previousUnit || group === undefined)
|
|
62
|
+
return undefined;
|
|
63
|
+
total += BigInt(group) * unit;
|
|
64
|
+
previousUnit = unit;
|
|
65
|
+
start = marker + 1;
|
|
66
|
+
}
|
|
67
|
+
if (start > 0 && start === value.length)
|
|
68
|
+
return total;
|
|
69
|
+
const tail = parseGroup(value.slice(start));
|
|
70
|
+
return tail === undefined ? undefined : total + BigInt(tail);
|
|
71
|
+
}
|
|
72
|
+
export function tryParseYen(value, options = {}) {
|
|
73
|
+
if (typeof value === "bigint")
|
|
74
|
+
return { ok: true, value };
|
|
75
|
+
if (typeof value === "number") {
|
|
76
|
+
if (!Number.isInteger(value))
|
|
77
|
+
return { ok: false, reason: "invalid_number" };
|
|
78
|
+
if (!Number.isSafeInteger(value))
|
|
79
|
+
return { ok: false, reason: "unsafe_integer" };
|
|
80
|
+
return { ok: true, value: BigInt(value) };
|
|
81
|
+
}
|
|
82
|
+
if (typeof value !== "string")
|
|
83
|
+
return { ok: false, reason: "invalid_type" };
|
|
84
|
+
let text = normalizeWidth(options.trim ? value.trim() : value);
|
|
85
|
+
if (text === "")
|
|
86
|
+
return { ok: false, reason: "empty" };
|
|
87
|
+
let negative = false;
|
|
88
|
+
if (text.startsWith("(") && text.endsWith(")")) {
|
|
89
|
+
negative = true;
|
|
90
|
+
text = text.slice(1, -1);
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
const sign = /^(マイナス|[-+])/u.exec(text)?.[0];
|
|
94
|
+
if (sign !== undefined) {
|
|
95
|
+
negative = sign !== "+";
|
|
96
|
+
text = text.slice(sign.length);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (text.startsWith("¥"))
|
|
100
|
+
text = text.slice(1);
|
|
101
|
+
else if (text.endsWith("円"))
|
|
102
|
+
text = text.slice(0, -1);
|
|
103
|
+
const amount = parseNumeral(text);
|
|
104
|
+
if (amount === undefined)
|
|
105
|
+
return { ok: false, reason: "invalid_format" };
|
|
106
|
+
return { ok: true, value: negative ? -amount : amount };
|
|
107
|
+
}
|
|
108
|
+
export function parseYen(value, options) {
|
|
109
|
+
const result = tryParseYen(value, options);
|
|
110
|
+
if (result.ok)
|
|
111
|
+
return result.value;
|
|
112
|
+
if (result.reason === "unsafe_integer")
|
|
113
|
+
throw new RangeError("Use bigint or text for an unsafe integer amount");
|
|
114
|
+
throw new TypeError(`Invalid yen amount (${result.reason})`);
|
|
115
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tiny-ja-money",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "Tiny TypeScript utilities for parsing, formatting, and calculating Japanese yen.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"import": "./dist/index.js"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"files": ["dist", "README.ja.md", "API.md", "CHANGELOG.md"],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"typecheck": "tsc --noEmit",
|
|
16
|
+
"build": "tsc",
|
|
17
|
+
"test": "npm run build && node --test",
|
|
18
|
+
"build:demo": "tsc --declaration false --outDir docs/lib",
|
|
19
|
+
"check:package": "npm run build && node scripts/check-package.mjs",
|
|
20
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run check:package"
|
|
21
|
+
},
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/fusaihanabi/tiny-ja-money.git"
|
|
25
|
+
},
|
|
26
|
+
"keywords": ["japanese", "yen", "jpy", "money", "bigint", "typescript"],
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"typescript": "5.9.3"
|
|
30
|
+
}
|
|
31
|
+
}
|