accounting.js 是一個用于格式化數字、貨幣和金額的輕量級庫,特別適合財務和會計應用。以下是其詳細使用說明:
安裝與引入
-
通過 npm 安裝:
bash
復制
下載
npm install accounting
引入:
javascript
復制
下載
const accounting = require('accounting');
-
直接引入腳本:
html
復制
下載
運行
<script src="path/to/accounting.js"></script>
核心方法
1. 格式化數字:formatNumber()
-
語法:
javascript
復制
下載
accounting.formatNumber(value, precision, thousand, decimal);
-
參數:
-
value
: 要格式化的數字。 -
precision
?(可選): 小數位數,默認為?0
。 -
thousand
?(可選): 千位分隔符,默認為?,
。 -
decimal
?(可選): 小數點符號,默認為?.
。
-
-
示例:
javascript
復制
下載
accounting.formatNumber(1234567.89); // "1,234,568" accounting.formatNumber(123456.789, 2, " ", ","); // "123 456,79"
2. 格式化貨幣:formatMoney()
-
語法:
javascript
復制
下載
accounting.formatMoney(value, symbol, precision, thousand, decimal, format);
-
參數:
-
value
: 要格式化的金額。 -
symbol
?(可選): 貨幣符號,默認為?$
。 -
precision
?(可選): 小數位數,默認為?2
。 -
thousand
?(可選): 千位分隔符,默認為?,
。 -
decimal
?(可選): 小數點符號,默認為?.
。 -
format
?(可選): 格式字符串,如?%s%v
(符號在前),默認為?%s%v
。
-
-
示例:
javascript
復制
下載
accounting.formatMoney(1234567.89); // "$1,234,567.89" accounting.formatMoney(-1234.56, "€", 2, ".", ",", "%v %s"); // "-1.234,56 €"
3. 解析格式化字符串:parse()
-
語法:
javascript
復制
下載
accounting.parse(string, decimal);
-
參數:
-
string
: 要解析的字符串(如?"£1,234.56"
)。 -
decimal
?(可選): 指定小數點符號,默認自動檢測。
-
-
示例:
javascript
復制
下載
accounting.parse("€1.234,56", ","); // 返回 1234.56
4. 格式化多列數據:formatColumn()
-
語法:
javascript
復制
下載
accounting.formatColumn(list, symbol, precision, thousand, decimal, format);
-
參數:同?
formatMoney()
,但處理數組。 -
示例:
javascript
復制
下載
accounting.formatColumn([123.5, 3456.49, 777888.99], "¥", 2); // 返回 ["¥123.50", "¥3,456.49", "¥777,888.99"]
全局配置
通過?accounting.settings
?修改默認行為:
javascript
復制
下載
accounting.settings = {currency: {symbol: "€", // 默認貨幣符號format: "%s%v", // 符號在前,數值在后decimal: ",", // 小數點thousand: ".", // 千位分隔符precision: 2 // 小數位數},number: {precision: 0,thousand: ",",decimal: "."} };
高級用法
-
自定義負數格式:
javascript
復制
下載
// 使用括號表示負數 accounting.formatMoney(-1234.56, "$", 2, ",", ".", "%s (%v)"); // 返回 "$ (1,234.56)"
-
處理超大數值(避免精度丟失):
javascript
復制
下載
accounting.formatMoney("12345678901234567890.12345"); // 正確解析字符串大數
注意事項
-
數值精度:JavaScript 浮點數計算可能存在精度問題,建議對極大/極小數值使用字符串形式。
-
國際化:根據地區調整?
thousand
、decimal
?和?symbol
,如歐洲格式:javascript
復制
下載
accounting.formatMoney(1234.56, "€", 2, ".", ",", "%v %s"); // "1.234,56 €"
-
多列對齊:使用?
formatColumn()
?確保表格中的金額對齊。
通過靈活配置參數,accounting.js 能夠滿足多種數字和貨幣格式需求,尤其適合財務系統、報表工具等場景。
安裝后,import accounting from "accounting";
提示
無法找到模塊“accounting”的聲明文件。“d:/MyCode/wylims/lims-client/node_modules/accounting/accounting.js”隱式擁有 "any" 類型。 嘗試使用 `npm i --save-dev @types/accounting` (如果存在),或者添加一個包含 `declare module 'accounting';` 的新聲明(.d.ts)文件ts(7016)
這個問題是因為 TypeScript 無法找到?accounting.js
?的類型聲明文件(*.d.ts
)。以下是幾種解決方案:
解決方案 1:安裝社區類型聲明(推薦嘗試)
雖然?accounting.js
?官方沒有提供 TypeScript 類型,但可以嘗試查找社區維護的類型聲明:
bash
復制
下載
npm install --save-dev @types/accounting
如果上述命令報錯(表示沒有社區類型),則需手動創建聲明文件。
解決方案 2:手動創建聲明文件
-
在項目中新建一個類型聲明文件(如?
src/types/accounting.d.ts
)。 -
添加以下內容:
typescript
復制
下載
// accounting.d.ts declare module 'accounting' {export function formatNumber(value: number | string,precision?: number,thousand?: string,decimal?: string): string;export function formatMoney(value: number | string,symbol?: string,precision?: number,thousand?: string,decimal?: string,format?: string): string;// 其他方法的聲明... }
-
在?
tsconfig.json
?中確保 TypeScript 能找到該文件:json
復制
下載
{"compilerOptions": {"typeRoots": ["./node_modules/@types", "./src/types"]} }
解決方案 3:快速忽略類型檢查(臨時方案)
在導入語句前添加?// @ts-ignore
?注釋:
typescript
復制
下載
// @ts-ignore import accounting from 'accounting';
注意:這會導致 TypeScript 跳過對該模塊的類型檢查,可能隱藏潛在錯誤。
解決方案 4:擴展全局類型
如果你希望全局聲明類型,在?accounting.d.ts
?中添加:
typescript
復制
下載
declare module 'accounting' {const accounting: {formatNumber: (...args: any[]) => string;formatMoney: (...args: any[]) => string;parse: (...args: any[]) => number;// 其他方法...};export default accounting; }
驗證是否生效
重啟 TypeScript 服務(如 VS Code 的 TypeScript 服務器)后,錯誤應消失。如果仍有問題,檢查:
-
聲明文件路徑是否在?
tsconfig.json
?的?typeRoots
?或?include
?范圍內。 -
聲明文件語法是否正確。
最終建議
-
優先嘗試?解決方案 2(手動聲明)。
-
如果需要完整類型支持,可自行完善?
accounting.d.ts
?中的類型定義。 -
如果庫使用頻率低,可用?解決方案 3?臨時繞過。
以下是使用?accounting.js
?的詳細示例,涵蓋常見場景和功能:
基礎用法示例
1. 格式化數字
typescript
復制
下載
// 引入庫 import accounting from "accounting";// 基本數字格式化 console.log(accounting.formatNumber(9876543.21)); // "9,876,543" console.log(accounting.formatNumber(1234.5678, 2)); // "1,234.57"(四舍五入) console.log(accounting.formatNumber(1234.5, 0, " ")); // "1 235"(千位用空格分隔)// 歐洲格式(千位用點,小數用逗號) console.log(accounting.formatNumber(123456.78, 2, ".", ",")); // "123.456,78"
2. 格式化貨幣
typescript
復制
下載
// 默認美元格式 console.log(accounting.formatMoney(12345.6789)); // "$12,345.68"// 自定義符號和格式 console.log(accounting.formatMoney(-1234.56,"€", // 符號2, // 小數位".", // 千位分隔符",", // 小數點"%v %s" // 格式(數值在前,符號在后) )); // "-1.234,56 €"// 處理大數值(使用字符串避免精度丟失) console.log(accounting.formatMoney("12345678901234567890.12345")); // "$12,345,678,901,234,567,890.12"
3. 解析貨幣字符串
typescript
復制
下載
// 解析帶符號的字符串 console.log(accounting.parse("£12,345.67")); // 12345.67 console.log(accounting.parse("1.234,56 €", ",")); // 1234.56(指定小數點逗號)// 解析負數 console.log(accounting.parse("-$5,000.25")); // -5000.25
4. 格式化多列數據
typescript
復制
下載
const prices = [1234.5, 67890.12, 45.6]; const formattedPrices = accounting.formatColumn(prices, "¥", 2);console.log(formattedPrices); // 輸出: ["¥1,234.50", "¥67,890.12", "¥45.60"]
全局配置示例
typescript
復制
下載
// 修改全局默認配置(適合歐洲貨幣格式) accounting.settings = {currency: {symbol: "€",format: "%v %s", // 數值在前,符號在后decimal: ",",thousand: ".",precision: 2},number: {precision: 2,thousand: " ",decimal: ","} };// 使用新配置格式化 console.log(accounting.formatMoney(1234.56)); // "1.234,56 €" console.log(accounting.formatNumber(1234567.89)); // "1 234 567,89"
高級用法示例
1. 自定義負數顯示
typescript
復制
下載
// 用括號包裹負數 const customFormat = accounting.formatMoney(-1234.56, "$", 2, ",", ".", "%s (%v)"); console.log(customFormat); // "$ (1,234.56)"
2. 處理多語言場景
typescript
復制
下載
// 切換為中文人民幣格式 const chineseFormat = accounting.formatMoney(12345.67,"¥",2,",",".","%s%v" ); console.log(chineseFormat); // "¥12,345.67"
3. 與其他工具結合(如表格渲染)
typescript
復制
下載
// 在 React/Vue 中渲染表格 const data = [{ product: "A", price: 1234.5 },{ product: "B", price: 6789.0 }, ];// 表格列格式化 const tableRows = data.map((item) => ({...item,price: accounting.formatMoney(item.price, "$", 2) }));// 輸出結果: // [ // { product: "A", price: "$1,234.50" }, // { product: "B", price: "$6,789.00" } // ]
常見問題解決
1. 浮點數精度問題
typescript
復制
下載
// 錯誤:JavaScript 浮點計算問題 console.log(0.1 + 0.2); // 0.30000000000000004// 正確:使用字符串初始化 console.log(accounting.formatMoney("0.1" + "0.2")); // "$0.30"
2. 處理空值或非數字
typescript
復制
下載
// 添加防御性代碼 const safeFormat = (value: any) => {if (isNaN(value)) return "N/A";return accounting.formatMoney(value); }; console.log(safeFormat("invalid")); // "N/A"
完整代碼示例
typescript
復制
下載
import accounting from "accounting";// 1. 配置全局格式 accounting.settings.currency.symbol = "¥"; accounting.settings.currency.precision = 0;// 2. 格式化價格列表 const prices = [1500, 2500, 98000]; const formattedPrices = accounting.formatColumn(prices);console.log(formattedPrices); // ["¥1,500", "¥2,500", "¥98,000"]// 3. 解析用戶輸入 const userInput = "¥12,345"; const parsedValue = accounting.parse(userInput); console.log(parsedValue); // 12345// 4. 生成財務報表 const reportData = {total: accounting.formatMoney(120000),tax: accounting.formatMoney(120000 * 0.1), }; console.log(reportData); // { total: "¥120,000", tax: "¥12,000" }
通過以上示例,你可以快速掌握?accounting.js
?的核心功能,適用于財務報表、價格顯示、數據導出等場景。