indian-number-kit 0.0.0-stage → 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pallav
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.md CHANGED
@@ -1,3 +1,218 @@
1
- # Temporary Holding Version
1
+ # indian-number-kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Format, convert and parse numbers in the Indian numbering system — lakhs and crores — in one tiny, type-safe package.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/indian-number-kit.svg)](https://www.npmjs.com/package/indian-number-kit)
6
+ [![npm downloads](https://img.shields.io/npm/dm/indian-number-kit.svg)](https://www.npmjs.com/package/indian-number-kit)
7
+ [![CI](https://github.com/Shivala-08/the-return-of-npm/actions/workflows/ci.yml/badge.svg)](https://github.com/Shivala-08/the-return-of-npm/actions/workflows/ci.yml)
8
+ [![licence](https://img.shields.io/npm/l/indian-number-kit.svg)](./LICENSE)
9
+ [![bundle size](https://img.shields.io/badge/gzip-2.4%20kB-brightgreen.svg)](#bundle-size)
10
+
11
+ Indian readers group digits as `12,34,567`, not `1,234,567`, and they say
12
+ "Twelve Lakh Thirty-Four Thousand Five Hundred Sixty-Seven". This package does
13
+ both, plus rupees, paise, compact forms and parsing. No dependencies, no
14
+ runtime surprises.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ npm install indian-number-kit
20
+ ```
21
+
22
+ Works in Node.js 18+ and every modern browser. Ships ESM, CommonJS and
23
+ TypeScript types.
24
+
25
+ ## Quick start
26
+
27
+ ```ts
28
+ import {
29
+ formatIndian,
30
+ toCurrency,
31
+ toWords,
32
+ toCurrencyWords,
33
+ toCompact,
34
+ parseIndian,
35
+ } from 'indian-number-kit';
36
+
37
+ formatIndian(1234567); // "12,34,567"
38
+ toCurrency(1234567.5); // "₹12,34,567.50"
39
+ toWords(1234567); // "Twelve Lakh Thirty-Four Thousand Five Hundred Sixty-Seven"
40
+ toCurrencyWords(150.5); // "One Hundred Fifty Rupees and Fifty Paise Only"
41
+ toCompact(12500000); // "1.25 Cr"
42
+ parseIndian('₹12,34,567.50'); // 1234567.5
43
+ ```
44
+
45
+ CommonJS works too:
46
+
47
+ ```js
48
+ const { formatIndian } = require('indian-number-kit');
49
+ ```
50
+
51
+ ## API
52
+
53
+ Every function accepts `number | string`. Strings may contain grouping commas,
54
+ whitespace and a `₹` / `Rs` / `INR` marker, so values copied straight from the
55
+ screen are fine. Invalid input (`NaN`, `Infinity`, `null`, `"abc"`, an empty
56
+ string) throws a `TypeError` that names the value it received.
57
+
58
+ ### `formatIndian(value, options?)`
59
+
60
+ Indian digit grouping: last three digits, then groups of two.
61
+
62
+ ```ts
63
+ formatIndian(1234567); // "12,34,567"
64
+ formatIndian(-1234567.891); // "-12,34,567.891"
65
+ formatIndian(-1234567.891, { decimals: 2 }); // "-12,34,567.89"
66
+ formatIndian(1234567, { separator: ' ' }); // "12 34 567"
67
+ formatIndian('₹12,34,567.50'); // "12,34,567.50"
68
+ formatIndian(1234, { decimals: 2 }); // "1,234.00"
69
+ ```
70
+
71
+ | Option | Type | Default | Meaning |
72
+ | ----------- | -------- | ----------------- | ----------------------------------------------------------------- |
73
+ | `decimals` | `number` | keep input digits | Digits after the point, rounded half away from zero |
74
+ | `separator` | `string` | `","` | Group separator |
75
+
76
+ ### `toCurrency(value, options?)`
77
+
78
+ Rupee symbol, two decimals by default.
79
+
80
+ ```ts
81
+ toCurrency(1234567.5); // "₹12,34,567.50"
82
+ toCurrency(0); // "₹0.00"
83
+ toCurrency(-42.5); // "-₹42.50"
84
+ toCurrency(1234567.5, { symbol: false }); // "12,34,567.50"
85
+ toCurrency(1234567.5, { symbol: 'Rs. ' });// "Rs. 12,34,567.50"
86
+ toCurrency(1234567.5, { decimals: 0 }); // "₹12,34,568"
87
+ ```
88
+
89
+ Options: `symbol` (`string | false`, default `"₹"`), plus `decimals` (default
90
+ `2`) and `separator` from `formatIndian`.
91
+
92
+ ### `toWords(value, options?)`
93
+
94
+ English words using lakh and crore.
95
+
96
+ ```ts
97
+ toWords(1234567); // "Twelve Lakh Thirty-Four Thousand Five Hundred Sixty-Seven"
98
+ toWords(-42); // "Minus Forty-Two"
99
+ toWords(0); // "Zero"
100
+ toWords(12.5); // "Twelve Point Five"
101
+ toWords(42, { casing: 'lower' }); // "forty-two"
102
+ toWords(42, { suffix: 'Only' }); // "Forty-Two Only"
103
+ ```
104
+
105
+ | Option | Type | Default | Meaning |
106
+ | -------- | --------------------------------- | --------- | ------------------------------ |
107
+ | `casing` | `'title' \| 'lower' \| 'upper'` | `'title'` | Letter casing of the output |
108
+ | `suffix` | `string` | none | Text appended, e.g. `"Only"` |
109
+
110
+ Values above `Number.MAX_SAFE_INTEGER` are supported when passed as strings:
111
+
112
+ ```ts
113
+ toWords('10000000000000'); // "Ten Lakh Crore"
114
+ ```
115
+
116
+ ### `toCurrencyWords(value, options?)`
117
+
118
+ Amounts in words, for invoices and cheques. Paise are rounded to two digits and
119
+ dropped when zero.
120
+
121
+ ```ts
122
+ toCurrencyWords(150.5); // "One Hundred Fifty Rupees and Fifty Paise Only"
123
+ toCurrencyWords(1); // "One Rupee Only"
124
+ toCurrencyWords(1.01); // "One Rupee and One Paisa Only"
125
+ toCurrencyWords(0); // "Zero Rupees Only"
126
+ toCurrencyWords(1, { suffix: '' }); // "One Rupee"
127
+ ```
128
+
129
+ Options are the same as `toWords`; the default suffix is `"Only"`.
130
+
131
+ ### `toCompact(value, options?)`
132
+
133
+ Short forms for cards, charts and dashboards.
134
+
135
+ ```ts
136
+ toCompact(999); // "999"
137
+ toCompact(1500); // "1.5 K"
138
+ toCompact(150000); // "1.5 L"
139
+ toCompact(12500000); // "1.25 Cr"
140
+ toCompact(12500000, { style: 'long' });// "1.25 Crore"
141
+ toCompact(12500000, { decimals: 0 }); // "1 Cr"
142
+ toCompact(-12500000); // "-1.25 Cr"
143
+ ```
144
+
145
+ | Option | Type | Default | Meaning |
146
+ | ---------- | --------------------- | --------- | ---------------------------------------- |
147
+ | `decimals` | `number` | `2` | Digits kept, trailing zeros trimmed |
148
+ | `style` | `'short' \| 'long'` | `'short'` | `"Cr"` vs `"Crore"` |
149
+
150
+ ### `parseIndian(input)`
151
+
152
+ Turns formatted text back into a number.
153
+
154
+ ```ts
155
+ parseIndian('₹12,34,567.50'); // 1234567.5
156
+ parseIndian('12,34,567'); // 1234567
157
+ parseIndian('Rs 1,000'); // 1000
158
+ parseIndian('1.5 Cr'); // 15000000
159
+ parseIndian('25 lakh'); // 2500000
160
+ ```
161
+
162
+ Throws a `TypeError` when the string is not a number.
163
+
164
+ ### Extras
165
+
166
+ ```ts
167
+ import { groupIndian, integerToWords } from 'indian-number-kit';
168
+
169
+ groupIndian('1234567'); // "12,34,567"
170
+ integerToWords(1234567n); // "Twelve Lakh Thirty-Four Thousand Five Hundred Sixty-Seven"
171
+ ```
172
+
173
+ ## Accuracy notes
174
+
175
+ - Formatting works on **digit strings and `BigInt`**, never on floating-point
176
+ arithmetic, so `1.005` at two decimals rounds to `1.01` and
177
+ `99.999` rounds to `100.00` as a person would expect.
178
+ - `number` inputs must be safe integers. Pass a **string** for anything larger;
179
+ integer strings up to 100 characters are accepted.
180
+ - Exponent notation (`1e21`) is expanded to plain digits first, up to 400
181
+ digits, so `1e308` formats correctly while `1e999` throws a clear
182
+ `TypeError` instead of allocating a huge string.
183
+ - A value that rounds to zero never carries a minus sign: `-0.001` at two
184
+ decimals is `0.00`, and `toCurrencyWords(-0.001)` is `"Zero Rupees Only"`.
185
+ - Options are type-checked: a non-string `separator`/`suffix` or a `symbol`
186
+ that is not a string or `false` throws rather than producing odd output.
187
+
188
+ ## Bundle size
189
+
190
+ | Build | Size |
191
+ | ---------------- | ------- |
192
+ | Minified ESM | 5.6 kB |
193
+ | Minified + gzip | 2.4 kB |
194
+ | Runtime deps | 0 |
195
+
196
+ `npm run size` enforces the budget in CI (3 kB gzipped, 6 kB minified).
197
+
198
+ ## Development
199
+
200
+ ```bash
201
+ npm install
202
+ npm test # run the test suite
203
+ npm run coverage # tests with a 95% coverage gate (currently 100%)
204
+ # includes fuzz/property tests checked against Intl and
205
+ # independent reference implementations
206
+ npm run lint
207
+ npm run typecheck
208
+ npm run build # dist/index.js, dist/index.cjs, dist/index.d.ts
209
+ ```
210
+
211
+ ## Contributing
212
+
213
+ Issues and pull requests are welcome. Please run `npm run coverage && npm run
214
+ lint` before opening a pull request — `prepublishOnly` runs the same checks.
215
+
216
+ ## Licence
217
+
218
+ [MIT](./LICENSE)
package/dist/index.cjs ADDED
@@ -0,0 +1,345 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ formatIndian: () => formatIndian,
24
+ groupIndian: () => groupIndian,
25
+ integerToWords: () => integerToWords,
26
+ parseIndian: () => parseIndian,
27
+ toCompact: () => toCompact,
28
+ toCurrency: () => toCurrency,
29
+ toCurrencyWords: () => toCurrencyWords,
30
+ toWords: () => toWords
31
+ });
32
+ module.exports = __toCommonJS(index_exports);
33
+
34
+ // src/validate.ts
35
+ var MAX_INPUT_LENGTH = 100;
36
+ var MAX_DECIMALS = 20;
37
+ var MAX_EXPANSION_DIGITS = 400;
38
+ var EXPONENTIAL = /^(-?)(\d+)(?:\.(\d+))?e([+-]?\d+)$/i;
39
+ var NUMERIC = /^(?:\d+(?:\.\d*)?|\.\d+)$/;
40
+ var PREFIX = "indian-number-kit: ";
41
+ function describe(value) {
42
+ return typeof value === "string" ? `"${value.slice(0, 40)}"` : String(value);
43
+ }
44
+ function invalidInput(value) {
45
+ return new TypeError(`${PREFIX}expected a finite number, received ${describe(value)}`);
46
+ }
47
+ function invalidOption(name, expected, value) {
48
+ return new RangeError(`${PREFIX}option "${name}" ${expected}, received ${describe(value)}`);
49
+ }
50
+ function tooLong() {
51
+ return new TypeError(`${PREFIX}input is limited to ${MAX_INPUT_LENGTH} characters`);
52
+ }
53
+ function tooLarge() {
54
+ return new TypeError(`${PREFIX}number is too large (limit: ${MAX_EXPANSION_DIGITS} digits)`);
55
+ }
56
+ function expandExponential(input) {
57
+ if (!/e/i.test(input)) return input;
58
+ const match = EXPONENTIAL.exec(input);
59
+ if (!match) return input;
60
+ const [, sign = "", whole = "0", fraction = "", exponentText = "0"] = match;
61
+ const digits = whole + fraction;
62
+ const shift = Number(exponentText) - fraction.length;
63
+ if (!Number.isFinite(shift) || digits.length + Math.abs(shift) > MAX_EXPANSION_DIGITS) {
64
+ throw tooLarge();
65
+ }
66
+ let plain;
67
+ if (shift >= 0) {
68
+ plain = digits + "0".repeat(shift);
69
+ } else {
70
+ const point = digits.length + shift;
71
+ plain = point > 0 ? `${digits.slice(0, point)}.${digits.slice(point)}` : `0.${"0".repeat(-point)}${digits}`;
72
+ }
73
+ return sign === "-" ? `-${plain}` : plain;
74
+ }
75
+ function assertDecimals(value, fallback) {
76
+ if (value === void 0) return fallback;
77
+ if (!Number.isInteger(value) || value < 0 || value > MAX_DECIMALS) {
78
+ throw invalidOption("decimals", `must be an integer between 0 and ${MAX_DECIMALS}`, value);
79
+ }
80
+ return value;
81
+ }
82
+ function assertStringOption(name, value, fallback) {
83
+ if (value === void 0) return fallback;
84
+ if (typeof value !== "string") throw invalidOption(name, "must be a string", value);
85
+ return value;
86
+ }
87
+ function normalize(input) {
88
+ let text;
89
+ if (typeof input === "number") {
90
+ if (!Number.isFinite(input)) throw invalidInput(input);
91
+ text = expandExponential(String(input));
92
+ } else if (typeof input === "string") {
93
+ if (input.length > MAX_INPUT_LENGTH) throw tooLong();
94
+ text = expandExponential(input);
95
+ } else {
96
+ throw invalidInput(input);
97
+ }
98
+ let cleaned = text.replace(/\s+/g, "").replace(/₹/g, "").replace(/^(?:rs\.?|inr)/i, "").replace(/(?:rs\.?|inr)$/i, "").replace(/,/g, "");
99
+ let negative = false;
100
+ if (cleaned.startsWith("-")) {
101
+ negative = true;
102
+ cleaned = cleaned.slice(1);
103
+ } else if (cleaned.startsWith("+")) {
104
+ cleaned = cleaned.slice(1);
105
+ }
106
+ if (!NUMERIC.test(cleaned)) throw invalidInput(input);
107
+ const dot = cleaned.indexOf(".");
108
+ const rawInt = dot === -1 ? cleaned : cleaned.slice(0, dot);
109
+ const rawFrac = dot === -1 ? "" : cleaned.slice(dot + 1);
110
+ const intPart = rawInt.replace(/^0+(?=\d)/, "") || "0";
111
+ const fracPart = rawFrac;
112
+ const isZero = intPart === "0" && /^0*$/.test(fracPart);
113
+ return {
114
+ negative: negative && !isZero,
115
+ intPart,
116
+ fracPart,
117
+ isZero
118
+ };
119
+ }
120
+
121
+ // src/format.ts
122
+ var DEFAULT_SEPARATOR = ",";
123
+ function groupIndian(intPart, separator = DEFAULT_SEPARATOR) {
124
+ const digits = intPart.replace(/^0+(?=\d)/, "");
125
+ if (digits.length <= 3) return digits;
126
+ const tail = digits.slice(-3);
127
+ const head = digits.slice(0, -3).replace(/\B(?=(\d{2})+(?!\d))/g, () => separator);
128
+ return `${head}${separator}${tail}`;
129
+ }
130
+ function incrementDigits(digits) {
131
+ return (BigInt(digits) + 1n).toString();
132
+ }
133
+ function roundDigits(intPart, fracPart, decimals) {
134
+ if (decimals >= fracPart.length) {
135
+ return { intPart, fracPart: fracPart.padEnd(decimals, "0") };
136
+ }
137
+ const kept = fracPart.slice(0, decimals);
138
+ const next = fracPart.charAt(decimals);
139
+ if (next < "5") return { intPart, fracPart: kept };
140
+ const combined = intPart + kept;
141
+ const bumped = incrementDigits(combined).padStart(combined.length, "0");
142
+ if (decimals === 0) return { intPart: bumped, fracPart: "" };
143
+ return {
144
+ intPart: bumped.slice(0, bumped.length - decimals),
145
+ fracPart: bumped.slice(-decimals)
146
+ };
147
+ }
148
+ function isZeroDigits(intPart, fracPart) {
149
+ return intPart === "0" && !/[1-9]/.test(fracPart);
150
+ }
151
+ function compose(negative, intPart, fracPart, separator, prefix = "") {
152
+ const body = groupIndian(intPart, separator) + (fracPart ? `.${fracPart}` : "");
153
+ const sign = negative && !isZeroDigits(intPart, fracPart) ? "-" : "";
154
+ return `${sign}${prefix}${body}`;
155
+ }
156
+ function formatIndian(value, options = {}) {
157
+ const separator = assertStringOption("separator", options.separator, DEFAULT_SEPARATOR);
158
+ const { negative, intPart, fracPart } = normalize(value);
159
+ if (options.decimals === void 0) return compose(negative, intPart, fracPart, separator);
160
+ const rounded = roundDigits(intPart, fracPart, assertDecimals(options.decimals, 0));
161
+ return compose(negative, rounded.intPart, rounded.fracPart, separator);
162
+ }
163
+ function toCurrency(value, options = {}) {
164
+ const decimals = assertDecimals(options.decimals, 2);
165
+ const separator = assertStringOption("separator", options.separator, DEFAULT_SEPARATOR);
166
+ const { symbol } = options;
167
+ if (symbol !== void 0 && symbol !== false && typeof symbol !== "string") {
168
+ throw invalidOption("symbol", "must be a string or false", symbol);
169
+ }
170
+ const { negative, intPart, fracPart } = normalize(value);
171
+ const rounded = roundDigits(intPart, fracPart, decimals);
172
+ const prefix = symbol === void 0 ? "\u20B9" : symbol === false ? "" : symbol;
173
+ return compose(negative, rounded.intPart, rounded.fracPart, separator, prefix);
174
+ }
175
+ var SHORT_UNITS = [
176
+ [10000000n, "Cr", "Crore"],
177
+ [100000n, "L", "Lakh"],
178
+ [1000n, "K", "Thousand"]
179
+ ];
180
+ function trimFraction(intPart, fracPart) {
181
+ const trimmed = fracPart.replace(/0+$/, "");
182
+ return trimmed ? `${intPart}.${trimmed}` : intPart;
183
+ }
184
+ function toCompact(value, options = {}) {
185
+ const decimals = assertDecimals(options.decimals, 2);
186
+ const style = options.style ?? "short";
187
+ if (style !== "short" && style !== "long") {
188
+ throw invalidOption("style", 'must be "short" or "long"', style);
189
+ }
190
+ const { negative, intPart, fracPart } = normalize(value);
191
+ const rounded = roundDigits(intPart, fracPart, decimals);
192
+ const unit = SHORT_UNITS.find((entry) => BigInt(rounded.intPart) >= entry[0]);
193
+ if (!unit) {
194
+ const plain = trimFraction(rounded.intPart, rounded.fracPart);
195
+ return `${negative && !isZeroDigits(rounded.intPart, rounded.fracPart) ? "-" : ""}${plain}`;
196
+ }
197
+ const scaled = BigInt(rounded.intPart + rounded.fracPart);
198
+ const divisor = unit[0];
199
+ const quotient = (scaled * 2n + divisor) / (divisor * 2n);
200
+ const digits = quotient.toString().padStart(decimals + 1, "0");
201
+ const whole = digits.slice(0, digits.length - decimals);
202
+ const fraction = digits.slice(digits.length - decimals);
203
+ const label = style === "short" ? unit[1] : unit[2];
204
+ const sign = negative && !isZeroDigits(whole, fraction) ? "-" : "";
205
+ return `${sign}${trimFraction(whole, fraction)} ${label}`;
206
+ }
207
+
208
+ // src/words.ts
209
+ var ONES = [
210
+ "Zero",
211
+ "One",
212
+ "Two",
213
+ "Three",
214
+ "Four",
215
+ "Five",
216
+ "Six",
217
+ "Seven",
218
+ "Eight",
219
+ "Nine",
220
+ "Ten",
221
+ "Eleven",
222
+ "Twelve",
223
+ "Thirteen",
224
+ "Fourteen",
225
+ "Fifteen",
226
+ "Sixteen",
227
+ "Seventeen",
228
+ "Eighteen",
229
+ "Nineteen"
230
+ ];
231
+ var TENS = [
232
+ "",
233
+ "",
234
+ "Twenty",
235
+ "Thirty",
236
+ "Forty",
237
+ "Fifty",
238
+ "Sixty",
239
+ "Seventy",
240
+ "Eighty",
241
+ "Ninety"
242
+ ];
243
+ var TEN_MILLION = 10000000n;
244
+ var HUNDRED_THOUSAND = 100000n;
245
+ var THOUSAND = 1000n;
246
+ var one = (n) => ONES[n];
247
+ var ten = (n) => TENS[n];
248
+ function belowHundred(n) {
249
+ if (n < 20) return one(n);
250
+ const tens = ten(Math.floor(n / 10));
251
+ const ones = n % 10;
252
+ return ones ? `${tens}-${one(ones)}` : tens;
253
+ }
254
+ function belowThousand(n) {
255
+ const hundreds = Math.floor(n / 100);
256
+ const rest = n % 100;
257
+ const parts = [];
258
+ if (hundreds) parts.push(`${one(hundreds)} Hundred`);
259
+ if (rest) parts.push(belowHundred(rest));
260
+ return parts.join(" ");
261
+ }
262
+ function integerToWords(value) {
263
+ if (value === 0n) return "Zero";
264
+ const crore = value / TEN_MILLION;
265
+ const afterCrore = value % TEN_MILLION;
266
+ const lakh = afterCrore / HUNDRED_THOUSAND;
267
+ const afterLakh = afterCrore % HUNDRED_THOUSAND;
268
+ const thousand = afterLakh / THOUSAND;
269
+ const rest = afterLakh % THOUSAND;
270
+ const parts = [];
271
+ if (crore > 0n) parts.push(`${integerToWords(crore)} Crore`);
272
+ if (lakh > 0n) parts.push(`${belowHundred(Number(lakh))} Lakh`);
273
+ if (thousand > 0n) parts.push(`${belowHundred(Number(thousand))} Thousand`);
274
+ if (rest > 0n) parts.push(belowThousand(Number(rest)));
275
+ return parts.join(" ");
276
+ }
277
+ function finish(text, { casing, suffix }, fallback = "") {
278
+ const tail = assertStringOption("suffix", suffix, fallback);
279
+ const sentence = tail ? `${text} ${tail}` : text;
280
+ if (casing === void 0 || casing === "title") return sentence;
281
+ if (casing === "lower") return sentence.toLowerCase();
282
+ if (casing === "upper") return sentence.toUpperCase();
283
+ throw invalidOption("casing", 'must be "title", "lower" or "upper"', casing);
284
+ }
285
+ function fractionToWords(fracPart) {
286
+ return [...fracPart].map((digit) => one(Number(digit))).join(" ");
287
+ }
288
+ function toWords(value, options = {}) {
289
+ const { negative, intPart, fracPart } = normalize(value);
290
+ let text = integerToWords(BigInt(intPart));
291
+ if (fracPart) text += ` Point ${fractionToWords(fracPart)}`;
292
+ if (negative) text = `Minus ${text}`;
293
+ return finish(text, options);
294
+ }
295
+ function toCurrencyWords(value, options = {}) {
296
+ const { negative, intPart, fracPart } = normalize(value);
297
+ const rounded = roundDigits(intPart, fracPart, 2);
298
+ const rupees = BigInt(rounded.intPart);
299
+ const paise = Number(rounded.fracPart.padEnd(2, "0").slice(0, 2));
300
+ const parts = [`${integerToWords(rupees)} ${rupees === 1n ? "Rupee" : "Rupees"}`];
301
+ if (paise > 0) parts.push(`and ${belowHundred(paise)} ${paise === 1 ? "Paisa" : "Paise"}`);
302
+ const amount = parts.join(" ");
303
+ const text = negative && (rupees > 0n || paise > 0) ? `Minus ${amount}` : amount;
304
+ return finish(text, options, "Only");
305
+ }
306
+
307
+ // src/parse.ts
308
+ var COMPACT_SUFFIXES = {
309
+ k: 1e3,
310
+ thousand: 1e3,
311
+ thousands: 1e3,
312
+ l: 1e5,
313
+ lakh: 1e5,
314
+ lakhs: 1e5,
315
+ cr: 1e7,
316
+ crore: 1e7,
317
+ crores: 1e7
318
+ };
319
+ var COMPACT = /(k|thousand|thousands|lakhs|lakh|l|crores|crore|cr)$/i;
320
+ var PLAIN = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
321
+ function parseIndian(input) {
322
+ if (typeof input !== "string") throw invalidInput(input);
323
+ if (input.length > MAX_INPUT_LENGTH) throw tooLong();
324
+ let text = input.trim().replace(/\s+/g, "").replace(/₹/g, "").replace(/^(?:rs\.?|inr)/i, "").replace(/(?:rs\.?|inr)$/i, "").replace(/,/g, "");
325
+ let multiplier = 1;
326
+ const compact = COMPACT.exec(text);
327
+ if (compact) {
328
+ text = text.slice(0, compact.index);
329
+ multiplier = COMPACT_SUFFIXES[compact[1].toLowerCase()];
330
+ }
331
+ if (!PLAIN.test(text)) throw invalidInput(input);
332
+ const result = Number(text) * multiplier;
333
+ return result === 0 ? 0 : result;
334
+ }
335
+ // Annotate the CommonJS export names for ESM import in node:
336
+ 0 && (module.exports = {
337
+ formatIndian,
338
+ groupIndian,
339
+ integerToWords,
340
+ parseIndian,
341
+ toCompact,
342
+ toCurrency,
343
+ toCurrencyWords,
344
+ toWords
345
+ });
@@ -0,0 +1,110 @@
1
+ /** Options accepted by {@link formatIndian}. */
2
+ interface FormatOptions {
3
+ /**
4
+ * Number of digits after the decimal point. Values are rounded half away
5
+ * from zero. When omitted, the decimals present in the input are kept.
6
+ */
7
+ decimals?: number;
8
+ /** Thousands/lakhs separator. Default: `","`. */
9
+ separator?: string;
10
+ }
11
+ /** Options accepted by {@link toCurrency}. */
12
+ interface CurrencyOptions extends FormatOptions {
13
+ /** Currency symbol, or `false` to omit it. Default: `"₹"`. */
14
+ symbol?: string | false;
15
+ }
16
+ /** Options accepted by {@link toWords} and {@link toCurrencyWords}. */
17
+ interface WordsOptions {
18
+ /** Letter casing of the output. Default: `"title"`. */
19
+ casing?: 'title' | 'lower' | 'upper';
20
+ /**
21
+ * Text appended to the end of the result, e.g. `"Only"`. Pass `""` to
22
+ * disable. Default: `"Only"` for {@link toCurrencyWords}, nothing for
23
+ * {@link toWords}.
24
+ */
25
+ suffix?: string;
26
+ }
27
+ /** Options accepted by {@link toCompact}. */
28
+ interface CompactOptions {
29
+ /** Digits kept after the decimal point, trailing zeros trimmed. Default: `2`. */
30
+ decimals?: number;
31
+ /** `"short"` gives `"1.25 Cr"`, `"long"` gives `"1.25 Crore"`. Default: `"short"`. */
32
+ style?: 'short' | 'long';
33
+ }
34
+ /** A value that any public function accepts. */
35
+ type IndianNumberInput = number | string;
36
+
37
+ /**
38
+ * Group `intPart` the Indian way: last 3 digits, then groups of 2.
39
+ *
40
+ * The separator is inserted through a replacer function so characters such as
41
+ * `$&` or `$1` are treated literally instead of as replacement patterns.
42
+ */
43
+ declare function groupIndian(intPart: string, separator?: string): string;
44
+ /**
45
+ * Format a number using Indian digit grouping.
46
+ *
47
+ * ```ts
48
+ * formatIndian(1234567); // "12,34,567"
49
+ * formatIndian(-1234567.891, { decimals: 2 }); // "-12,34,567.89"
50
+ * formatIndian(1234567.891, { separator: ' ' }); // "12 34 567.891"
51
+ * ```
52
+ */
53
+ declare function formatIndian(value: IndianNumberInput, options?: FormatOptions): string;
54
+ /**
55
+ * Format a value as Indian rupees, with the symbol and paise.
56
+ *
57
+ * ```ts
58
+ * toCurrency(1234567.5); // "₹12,34,567.50"
59
+ * toCurrency(1234567.5, { symbol: false }); // "12,34,567.50"
60
+ * toCurrency(1234567.5, { symbol: 'Rs. ' }); // "Rs. 12,34,567.50"
61
+ * ```
62
+ */
63
+ declare function toCurrency(value: IndianNumberInput, options?: CurrencyOptions): string;
64
+ /**
65
+ * Shorten a large number using K / L / Cr (or Thousand / Lakh / Crore).
66
+ *
67
+ * ```ts
68
+ * toCompact(12500000); // "1.25 Cr"
69
+ * toCompact(12500000, { style: 'long' }); // "1.25 Crore"
70
+ * toCompact(12500000, { decimals: 0 }); // "1 Cr"
71
+ * ```
72
+ */
73
+ declare function toCompact(value: IndianNumberInput, options?: CompactOptions): string;
74
+
75
+ /** Words for a whole number, recursing so 1e12 becomes "One Lakh Crore". */
76
+ declare function integerToWords(value: bigint): string;
77
+ /**
78
+ * Convert a number to English words in the Indian system.
79
+ *
80
+ * ```ts
81
+ * toWords(1234567); // "Twelve Lakh Thirty-Four Thousand Five Hundred Sixty-Seven"
82
+ * toWords(-42); // "Minus Forty-Two"
83
+ * toWords(12.5); // "Twelve Point Five"
84
+ * ```
85
+ */
86
+ declare function toWords(value: IndianNumberInput, options?: WordsOptions): string;
87
+ /**
88
+ * Convert a value to rupees and paise in words.
89
+ *
90
+ * ```ts
91
+ * toCurrencyWords(150.5); // "One Hundred Fifty Rupees and Fifty Paise Only"
92
+ * toCurrencyWords(1); // "One Rupee Only"
93
+ * ```
94
+ */
95
+ declare function toCurrencyWords(value: IndianNumberInput, options?: WordsOptions): string;
96
+
97
+ /**
98
+ * Parse a formatted Indian number back into a `number`.
99
+ *
100
+ * Accepts commas, the `₹` / `Rs` / `INR` marker, whitespace and — as a bonus —
101
+ * compact suffixes (`"1.5 Cr"` → `15000000`).
102
+ *
103
+ * ```ts
104
+ * parseIndian('₹12,34,567.50'); // 1234567.5
105
+ * parseIndian('1.5 Cr'); // 15000000
106
+ * ```
107
+ */
108
+ declare function parseIndian(input: string): number;
109
+
110
+ export { type CompactOptions, type CurrencyOptions, type FormatOptions, type IndianNumberInput, type WordsOptions, formatIndian, groupIndian, integerToWords, parseIndian, toCompact, toCurrency, toCurrencyWords, toWords };
@@ -0,0 +1,110 @@
1
+ /** Options accepted by {@link formatIndian}. */
2
+ interface FormatOptions {
3
+ /**
4
+ * Number of digits after the decimal point. Values are rounded half away
5
+ * from zero. When omitted, the decimals present in the input are kept.
6
+ */
7
+ decimals?: number;
8
+ /** Thousands/lakhs separator. Default: `","`. */
9
+ separator?: string;
10
+ }
11
+ /** Options accepted by {@link toCurrency}. */
12
+ interface CurrencyOptions extends FormatOptions {
13
+ /** Currency symbol, or `false` to omit it. Default: `"₹"`. */
14
+ symbol?: string | false;
15
+ }
16
+ /** Options accepted by {@link toWords} and {@link toCurrencyWords}. */
17
+ interface WordsOptions {
18
+ /** Letter casing of the output. Default: `"title"`. */
19
+ casing?: 'title' | 'lower' | 'upper';
20
+ /**
21
+ * Text appended to the end of the result, e.g. `"Only"`. Pass `""` to
22
+ * disable. Default: `"Only"` for {@link toCurrencyWords}, nothing for
23
+ * {@link toWords}.
24
+ */
25
+ suffix?: string;
26
+ }
27
+ /** Options accepted by {@link toCompact}. */
28
+ interface CompactOptions {
29
+ /** Digits kept after the decimal point, trailing zeros trimmed. Default: `2`. */
30
+ decimals?: number;
31
+ /** `"short"` gives `"1.25 Cr"`, `"long"` gives `"1.25 Crore"`. Default: `"short"`. */
32
+ style?: 'short' | 'long';
33
+ }
34
+ /** A value that any public function accepts. */
35
+ type IndianNumberInput = number | string;
36
+
37
+ /**
38
+ * Group `intPart` the Indian way: last 3 digits, then groups of 2.
39
+ *
40
+ * The separator is inserted through a replacer function so characters such as
41
+ * `$&` or `$1` are treated literally instead of as replacement patterns.
42
+ */
43
+ declare function groupIndian(intPart: string, separator?: string): string;
44
+ /**
45
+ * Format a number using Indian digit grouping.
46
+ *
47
+ * ```ts
48
+ * formatIndian(1234567); // "12,34,567"
49
+ * formatIndian(-1234567.891, { decimals: 2 }); // "-12,34,567.89"
50
+ * formatIndian(1234567.891, { separator: ' ' }); // "12 34 567.891"
51
+ * ```
52
+ */
53
+ declare function formatIndian(value: IndianNumberInput, options?: FormatOptions): string;
54
+ /**
55
+ * Format a value as Indian rupees, with the symbol and paise.
56
+ *
57
+ * ```ts
58
+ * toCurrency(1234567.5); // "₹12,34,567.50"
59
+ * toCurrency(1234567.5, { symbol: false }); // "12,34,567.50"
60
+ * toCurrency(1234567.5, { symbol: 'Rs. ' }); // "Rs. 12,34,567.50"
61
+ * ```
62
+ */
63
+ declare function toCurrency(value: IndianNumberInput, options?: CurrencyOptions): string;
64
+ /**
65
+ * Shorten a large number using K / L / Cr (or Thousand / Lakh / Crore).
66
+ *
67
+ * ```ts
68
+ * toCompact(12500000); // "1.25 Cr"
69
+ * toCompact(12500000, { style: 'long' }); // "1.25 Crore"
70
+ * toCompact(12500000, { decimals: 0 }); // "1 Cr"
71
+ * ```
72
+ */
73
+ declare function toCompact(value: IndianNumberInput, options?: CompactOptions): string;
74
+
75
+ /** Words for a whole number, recursing so 1e12 becomes "One Lakh Crore". */
76
+ declare function integerToWords(value: bigint): string;
77
+ /**
78
+ * Convert a number to English words in the Indian system.
79
+ *
80
+ * ```ts
81
+ * toWords(1234567); // "Twelve Lakh Thirty-Four Thousand Five Hundred Sixty-Seven"
82
+ * toWords(-42); // "Minus Forty-Two"
83
+ * toWords(12.5); // "Twelve Point Five"
84
+ * ```
85
+ */
86
+ declare function toWords(value: IndianNumberInput, options?: WordsOptions): string;
87
+ /**
88
+ * Convert a value to rupees and paise in words.
89
+ *
90
+ * ```ts
91
+ * toCurrencyWords(150.5); // "One Hundred Fifty Rupees and Fifty Paise Only"
92
+ * toCurrencyWords(1); // "One Rupee Only"
93
+ * ```
94
+ */
95
+ declare function toCurrencyWords(value: IndianNumberInput, options?: WordsOptions): string;
96
+
97
+ /**
98
+ * Parse a formatted Indian number back into a `number`.
99
+ *
100
+ * Accepts commas, the `₹` / `Rs` / `INR` marker, whitespace and — as a bonus —
101
+ * compact suffixes (`"1.5 Cr"` → `15000000`).
102
+ *
103
+ * ```ts
104
+ * parseIndian('₹12,34,567.50'); // 1234567.5
105
+ * parseIndian('1.5 Cr'); // 15000000
106
+ * ```
107
+ */
108
+ declare function parseIndian(input: string): number;
109
+
110
+ export { type CompactOptions, type CurrencyOptions, type FormatOptions, type IndianNumberInput, type WordsOptions, formatIndian, groupIndian, integerToWords, parseIndian, toCompact, toCurrency, toCurrencyWords, toWords };
package/dist/index.js ADDED
@@ -0,0 +1,311 @@
1
+ // src/validate.ts
2
+ var MAX_INPUT_LENGTH = 100;
3
+ var MAX_DECIMALS = 20;
4
+ var MAX_EXPANSION_DIGITS = 400;
5
+ var EXPONENTIAL = /^(-?)(\d+)(?:\.(\d+))?e([+-]?\d+)$/i;
6
+ var NUMERIC = /^(?:\d+(?:\.\d*)?|\.\d+)$/;
7
+ var PREFIX = "indian-number-kit: ";
8
+ function describe(value) {
9
+ return typeof value === "string" ? `"${value.slice(0, 40)}"` : String(value);
10
+ }
11
+ function invalidInput(value) {
12
+ return new TypeError(`${PREFIX}expected a finite number, received ${describe(value)}`);
13
+ }
14
+ function invalidOption(name, expected, value) {
15
+ return new RangeError(`${PREFIX}option "${name}" ${expected}, received ${describe(value)}`);
16
+ }
17
+ function tooLong() {
18
+ return new TypeError(`${PREFIX}input is limited to ${MAX_INPUT_LENGTH} characters`);
19
+ }
20
+ function tooLarge() {
21
+ return new TypeError(`${PREFIX}number is too large (limit: ${MAX_EXPANSION_DIGITS} digits)`);
22
+ }
23
+ function expandExponential(input) {
24
+ if (!/e/i.test(input)) return input;
25
+ const match = EXPONENTIAL.exec(input);
26
+ if (!match) return input;
27
+ const [, sign = "", whole = "0", fraction = "", exponentText = "0"] = match;
28
+ const digits = whole + fraction;
29
+ const shift = Number(exponentText) - fraction.length;
30
+ if (!Number.isFinite(shift) || digits.length + Math.abs(shift) > MAX_EXPANSION_DIGITS) {
31
+ throw tooLarge();
32
+ }
33
+ let plain;
34
+ if (shift >= 0) {
35
+ plain = digits + "0".repeat(shift);
36
+ } else {
37
+ const point = digits.length + shift;
38
+ plain = point > 0 ? `${digits.slice(0, point)}.${digits.slice(point)}` : `0.${"0".repeat(-point)}${digits}`;
39
+ }
40
+ return sign === "-" ? `-${plain}` : plain;
41
+ }
42
+ function assertDecimals(value, fallback) {
43
+ if (value === void 0) return fallback;
44
+ if (!Number.isInteger(value) || value < 0 || value > MAX_DECIMALS) {
45
+ throw invalidOption("decimals", `must be an integer between 0 and ${MAX_DECIMALS}`, value);
46
+ }
47
+ return value;
48
+ }
49
+ function assertStringOption(name, value, fallback) {
50
+ if (value === void 0) return fallback;
51
+ if (typeof value !== "string") throw invalidOption(name, "must be a string", value);
52
+ return value;
53
+ }
54
+ function normalize(input) {
55
+ let text;
56
+ if (typeof input === "number") {
57
+ if (!Number.isFinite(input)) throw invalidInput(input);
58
+ text = expandExponential(String(input));
59
+ } else if (typeof input === "string") {
60
+ if (input.length > MAX_INPUT_LENGTH) throw tooLong();
61
+ text = expandExponential(input);
62
+ } else {
63
+ throw invalidInput(input);
64
+ }
65
+ let cleaned = text.replace(/\s+/g, "").replace(/₹/g, "").replace(/^(?:rs\.?|inr)/i, "").replace(/(?:rs\.?|inr)$/i, "").replace(/,/g, "");
66
+ let negative = false;
67
+ if (cleaned.startsWith("-")) {
68
+ negative = true;
69
+ cleaned = cleaned.slice(1);
70
+ } else if (cleaned.startsWith("+")) {
71
+ cleaned = cleaned.slice(1);
72
+ }
73
+ if (!NUMERIC.test(cleaned)) throw invalidInput(input);
74
+ const dot = cleaned.indexOf(".");
75
+ const rawInt = dot === -1 ? cleaned : cleaned.slice(0, dot);
76
+ const rawFrac = dot === -1 ? "" : cleaned.slice(dot + 1);
77
+ const intPart = rawInt.replace(/^0+(?=\d)/, "") || "0";
78
+ const fracPart = rawFrac;
79
+ const isZero = intPart === "0" && /^0*$/.test(fracPart);
80
+ return {
81
+ negative: negative && !isZero,
82
+ intPart,
83
+ fracPart,
84
+ isZero
85
+ };
86
+ }
87
+
88
+ // src/format.ts
89
+ var DEFAULT_SEPARATOR = ",";
90
+ function groupIndian(intPart, separator = DEFAULT_SEPARATOR) {
91
+ const digits = intPart.replace(/^0+(?=\d)/, "");
92
+ if (digits.length <= 3) return digits;
93
+ const tail = digits.slice(-3);
94
+ const head = digits.slice(0, -3).replace(/\B(?=(\d{2})+(?!\d))/g, () => separator);
95
+ return `${head}${separator}${tail}`;
96
+ }
97
+ function incrementDigits(digits) {
98
+ return (BigInt(digits) + 1n).toString();
99
+ }
100
+ function roundDigits(intPart, fracPart, decimals) {
101
+ if (decimals >= fracPart.length) {
102
+ return { intPart, fracPart: fracPart.padEnd(decimals, "0") };
103
+ }
104
+ const kept = fracPart.slice(0, decimals);
105
+ const next = fracPart.charAt(decimals);
106
+ if (next < "5") return { intPart, fracPart: kept };
107
+ const combined = intPart + kept;
108
+ const bumped = incrementDigits(combined).padStart(combined.length, "0");
109
+ if (decimals === 0) return { intPart: bumped, fracPart: "" };
110
+ return {
111
+ intPart: bumped.slice(0, bumped.length - decimals),
112
+ fracPart: bumped.slice(-decimals)
113
+ };
114
+ }
115
+ function isZeroDigits(intPart, fracPart) {
116
+ return intPart === "0" && !/[1-9]/.test(fracPart);
117
+ }
118
+ function compose(negative, intPart, fracPart, separator, prefix = "") {
119
+ const body = groupIndian(intPart, separator) + (fracPart ? `.${fracPart}` : "");
120
+ const sign = negative && !isZeroDigits(intPart, fracPart) ? "-" : "";
121
+ return `${sign}${prefix}${body}`;
122
+ }
123
+ function formatIndian(value, options = {}) {
124
+ const separator = assertStringOption("separator", options.separator, DEFAULT_SEPARATOR);
125
+ const { negative, intPart, fracPart } = normalize(value);
126
+ if (options.decimals === void 0) return compose(negative, intPart, fracPart, separator);
127
+ const rounded = roundDigits(intPart, fracPart, assertDecimals(options.decimals, 0));
128
+ return compose(negative, rounded.intPart, rounded.fracPart, separator);
129
+ }
130
+ function toCurrency(value, options = {}) {
131
+ const decimals = assertDecimals(options.decimals, 2);
132
+ const separator = assertStringOption("separator", options.separator, DEFAULT_SEPARATOR);
133
+ const { symbol } = options;
134
+ if (symbol !== void 0 && symbol !== false && typeof symbol !== "string") {
135
+ throw invalidOption("symbol", "must be a string or false", symbol);
136
+ }
137
+ const { negative, intPart, fracPart } = normalize(value);
138
+ const rounded = roundDigits(intPart, fracPart, decimals);
139
+ const prefix = symbol === void 0 ? "\u20B9" : symbol === false ? "" : symbol;
140
+ return compose(negative, rounded.intPart, rounded.fracPart, separator, prefix);
141
+ }
142
+ var SHORT_UNITS = [
143
+ [10000000n, "Cr", "Crore"],
144
+ [100000n, "L", "Lakh"],
145
+ [1000n, "K", "Thousand"]
146
+ ];
147
+ function trimFraction(intPart, fracPart) {
148
+ const trimmed = fracPart.replace(/0+$/, "");
149
+ return trimmed ? `${intPart}.${trimmed}` : intPart;
150
+ }
151
+ function toCompact(value, options = {}) {
152
+ const decimals = assertDecimals(options.decimals, 2);
153
+ const style = options.style ?? "short";
154
+ if (style !== "short" && style !== "long") {
155
+ throw invalidOption("style", 'must be "short" or "long"', style);
156
+ }
157
+ const { negative, intPart, fracPart } = normalize(value);
158
+ const rounded = roundDigits(intPart, fracPart, decimals);
159
+ const unit = SHORT_UNITS.find((entry) => BigInt(rounded.intPart) >= entry[0]);
160
+ if (!unit) {
161
+ const plain = trimFraction(rounded.intPart, rounded.fracPart);
162
+ return `${negative && !isZeroDigits(rounded.intPart, rounded.fracPart) ? "-" : ""}${plain}`;
163
+ }
164
+ const scaled = BigInt(rounded.intPart + rounded.fracPart);
165
+ const divisor = unit[0];
166
+ const quotient = (scaled * 2n + divisor) / (divisor * 2n);
167
+ const digits = quotient.toString().padStart(decimals + 1, "0");
168
+ const whole = digits.slice(0, digits.length - decimals);
169
+ const fraction = digits.slice(digits.length - decimals);
170
+ const label = style === "short" ? unit[1] : unit[2];
171
+ const sign = negative && !isZeroDigits(whole, fraction) ? "-" : "";
172
+ return `${sign}${trimFraction(whole, fraction)} ${label}`;
173
+ }
174
+
175
+ // src/words.ts
176
+ var ONES = [
177
+ "Zero",
178
+ "One",
179
+ "Two",
180
+ "Three",
181
+ "Four",
182
+ "Five",
183
+ "Six",
184
+ "Seven",
185
+ "Eight",
186
+ "Nine",
187
+ "Ten",
188
+ "Eleven",
189
+ "Twelve",
190
+ "Thirteen",
191
+ "Fourteen",
192
+ "Fifteen",
193
+ "Sixteen",
194
+ "Seventeen",
195
+ "Eighteen",
196
+ "Nineteen"
197
+ ];
198
+ var TENS = [
199
+ "",
200
+ "",
201
+ "Twenty",
202
+ "Thirty",
203
+ "Forty",
204
+ "Fifty",
205
+ "Sixty",
206
+ "Seventy",
207
+ "Eighty",
208
+ "Ninety"
209
+ ];
210
+ var TEN_MILLION = 10000000n;
211
+ var HUNDRED_THOUSAND = 100000n;
212
+ var THOUSAND = 1000n;
213
+ var one = (n) => ONES[n];
214
+ var ten = (n) => TENS[n];
215
+ function belowHundred(n) {
216
+ if (n < 20) return one(n);
217
+ const tens = ten(Math.floor(n / 10));
218
+ const ones = n % 10;
219
+ return ones ? `${tens}-${one(ones)}` : tens;
220
+ }
221
+ function belowThousand(n) {
222
+ const hundreds = Math.floor(n / 100);
223
+ const rest = n % 100;
224
+ const parts = [];
225
+ if (hundreds) parts.push(`${one(hundreds)} Hundred`);
226
+ if (rest) parts.push(belowHundred(rest));
227
+ return parts.join(" ");
228
+ }
229
+ function integerToWords(value) {
230
+ if (value === 0n) return "Zero";
231
+ const crore = value / TEN_MILLION;
232
+ const afterCrore = value % TEN_MILLION;
233
+ const lakh = afterCrore / HUNDRED_THOUSAND;
234
+ const afterLakh = afterCrore % HUNDRED_THOUSAND;
235
+ const thousand = afterLakh / THOUSAND;
236
+ const rest = afterLakh % THOUSAND;
237
+ const parts = [];
238
+ if (crore > 0n) parts.push(`${integerToWords(crore)} Crore`);
239
+ if (lakh > 0n) parts.push(`${belowHundred(Number(lakh))} Lakh`);
240
+ if (thousand > 0n) parts.push(`${belowHundred(Number(thousand))} Thousand`);
241
+ if (rest > 0n) parts.push(belowThousand(Number(rest)));
242
+ return parts.join(" ");
243
+ }
244
+ function finish(text, { casing, suffix }, fallback = "") {
245
+ const tail = assertStringOption("suffix", suffix, fallback);
246
+ const sentence = tail ? `${text} ${tail}` : text;
247
+ if (casing === void 0 || casing === "title") return sentence;
248
+ if (casing === "lower") return sentence.toLowerCase();
249
+ if (casing === "upper") return sentence.toUpperCase();
250
+ throw invalidOption("casing", 'must be "title", "lower" or "upper"', casing);
251
+ }
252
+ function fractionToWords(fracPart) {
253
+ return [...fracPart].map((digit) => one(Number(digit))).join(" ");
254
+ }
255
+ function toWords(value, options = {}) {
256
+ const { negative, intPart, fracPart } = normalize(value);
257
+ let text = integerToWords(BigInt(intPart));
258
+ if (fracPart) text += ` Point ${fractionToWords(fracPart)}`;
259
+ if (negative) text = `Minus ${text}`;
260
+ return finish(text, options);
261
+ }
262
+ function toCurrencyWords(value, options = {}) {
263
+ const { negative, intPart, fracPart } = normalize(value);
264
+ const rounded = roundDigits(intPart, fracPart, 2);
265
+ const rupees = BigInt(rounded.intPart);
266
+ const paise = Number(rounded.fracPart.padEnd(2, "0").slice(0, 2));
267
+ const parts = [`${integerToWords(rupees)} ${rupees === 1n ? "Rupee" : "Rupees"}`];
268
+ if (paise > 0) parts.push(`and ${belowHundred(paise)} ${paise === 1 ? "Paisa" : "Paise"}`);
269
+ const amount = parts.join(" ");
270
+ const text = negative && (rupees > 0n || paise > 0) ? `Minus ${amount}` : amount;
271
+ return finish(text, options, "Only");
272
+ }
273
+
274
+ // src/parse.ts
275
+ var COMPACT_SUFFIXES = {
276
+ k: 1e3,
277
+ thousand: 1e3,
278
+ thousands: 1e3,
279
+ l: 1e5,
280
+ lakh: 1e5,
281
+ lakhs: 1e5,
282
+ cr: 1e7,
283
+ crore: 1e7,
284
+ crores: 1e7
285
+ };
286
+ var COMPACT = /(k|thousand|thousands|lakhs|lakh|l|crores|crore|cr)$/i;
287
+ var PLAIN = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
288
+ function parseIndian(input) {
289
+ if (typeof input !== "string") throw invalidInput(input);
290
+ if (input.length > MAX_INPUT_LENGTH) throw tooLong();
291
+ let text = input.trim().replace(/\s+/g, "").replace(/₹/g, "").replace(/^(?:rs\.?|inr)/i, "").replace(/(?:rs\.?|inr)$/i, "").replace(/,/g, "");
292
+ let multiplier = 1;
293
+ const compact = COMPACT.exec(text);
294
+ if (compact) {
295
+ text = text.slice(0, compact.index);
296
+ multiplier = COMPACT_SUFFIXES[compact[1].toLowerCase()];
297
+ }
298
+ if (!PLAIN.test(text)) throw invalidInput(input);
299
+ const result = Number(text) * multiplier;
300
+ return result === 0 ? 0 : result;
301
+ }
302
+ export {
303
+ formatIndian,
304
+ groupIndian,
305
+ integerToWords,
306
+ parseIndian,
307
+ toCompact,
308
+ toCurrency,
309
+ toCurrencyWords,
310
+ toWords
311
+ };
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "indian-number-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Format, convert and parse numbers in the Indian numbering system (lakh, crore).",
5
+ "keywords": [
6
+ "indian",
7
+ "lakh",
8
+ "crore",
9
+ "number-format",
10
+ "currency",
11
+ "rupee",
12
+ "number-to-words",
13
+ "inr",
14
+ "en-in"
15
+ ],
16
+ "license": "MIT",
17
+ "author": "Pallav",
18
+ "type": "module",
19
+ "main": "./dist/index.cjs",
20
+ "module": "./dist/index.js",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js",
26
+ "require": "./dist/index.cjs"
27
+ }
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "sideEffects": false,
35
+ "engines": {
36
+ "node": ">=18"
37
+ },
38
+ "scripts": {
39
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
40
+ "build:min": "tsup src/index.ts --format esm --minify --out-dir .size",
41
+ "test": "vitest run",
42
+ "coverage": "vitest run --coverage",
43
+ "typecheck": "tsc --noEmit",
44
+ "lint": "eslint src test",
45
+ "format": "prettier --write .",
46
+ "size": "npm run build:min >/dev/null && node scripts/size.mjs",
47
+ "prepublishOnly": "npm run lint && npm run typecheck && npm run coverage && npm run build",
48
+ "check:readme": "npm run build >/dev/null && node scripts/check-readme.mjs"
49
+ },
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "git+https://github.com/Shivala-08/the-return-of-npm.git"
53
+ },
54
+ "devDependencies": {
55
+ "@eslint/js": "^9.39.1",
56
+ "@types/node": "^22.9.0",
57
+ "@vitest/coverage-v8": "^3.2.4",
58
+ "eslint": "^9.39.1",
59
+ "prettier": "^3.6.2",
60
+ "tsup": "^8.5.0",
61
+ "typescript": "^5.9.3",
62
+ "typescript-eslint": "^8.46.4",
63
+ "vitest": "^3.2.4"
64
+ },
65
+ "homepage": "https://github.com/Shivala-08/the-return-of-npm#readme",
66
+ "bugs": {
67
+ "url": "https://github.com/Shivala-08/the-return-of-npm/issues"
68
+ }
69
+ }