搜尋
首頁web前端js教程javascript數字格式化通用類別 accounting.js使用_javascript技巧

程式碼內容及下載位址
accounting.js程式碼如下:

複製程式碼 程式碼如下:

/*!
* accounting.js v0.3.2
* Copyright 2011, Joss Crowcroft
*
* Freely distributable under the MIT license.
* Portions of accounting.js are inspired or borrowed from underscore.js
*
* Full details and documentation:
* http://josscrowcroft.github.com/accounting.js/
*/
(function(root, undefined) {
/* --- Setup --- */
// Create the local library object, to be exported or referenced globally later
var lib = {};
// Current version
lib.version = '0.3.2';
/* --- Exposed settings --- */
// The library's settings configuration object. Contains default parameters for
// currency and number formatting
lib.settings = {
currency: {
symbol : "$", // default currency symbol is '$'
format : "%s%v", // controls output: %s = symbol, %v = value (can be object, see docs)
decimal : ".", // decimal point separator
thousand : ",", // thousands separator
precision : 2, // decimal places
grouping : 3 // digit grouping (not implemented yet)
},
number: {
precision : 0, // default precision on numbers is 0
grouping : 3, // digit grouping (not implemented yet)
thousand : ",",
decimal : "."
}
};
/* --- Internal Helper Methods --- */
// Store reference to possibly-available ECMAScript 5 methods for later
var nativeMap = Array.prototype.map,
nativeIsArray = Array.isArray,
toString = Object.prototype.toString;
/**
* Tests whether supplied parameter is a string
* from underscore.js
*/
function isString(obj) {
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
}
/**
* Tests whether supplied parameter is a string
* from underscore.js, delegates to ECMA5's native Array.isArray
*/
function isArray(obj) {
return nativeIsArray ? nativeIsArray(obj) : toString.call(obj) === '[object Array]';
}
/**
* Tests whether supplied parameter is a true object
*/
function isObject(obj) {
return obj && toString.call(obj) === '[object Object]';
}
/**
* Extends an object with a defaults object, similar to underscore's _.defaults
*
* Used for abstracting parameter handling from API methods
*/
function defaults(object, defs) {
var key;
object = object || {};
defs = defs || {};
// Iterate over object non-prototype properties:
for (key in defs) {
if (defs.hasOwnProperty(key)) {
// Replace values with defaults only if undefined (allow empty/zero values):
if (object[key] == null) object[key] = defs[key];
}
}
return object;
}
/**
* Implementation of `Array.map()` for iteration loops
*
* Returns a new Array as a result of calling `iterator` on each array value.
* Defers to native Array.map if available
*/
function map(obj, iterator, context) {
var results = [], i, j;
if (!obj) return results;
// Use native .map method if it exists:
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
// Fallback for native .map:
for (i = 0, j = obj.length; i results[i] = iterator.call(context, obj[i], i, obj);
}
return results;
}
/**
* Check and normalise the value of precision (must be positive integer)
*/
function checkPrecision(val, base) {
val = Math.round(Math.abs(val));
return isNaN(val)? base : val;
}
/**
* Parses a format string or object and returns format obj for use in rendering
*
* `format` is either a string with the default (positive) format, or object
* containing `pos` (required), `neg` and `zero` values (or a function returning
* either a string or object)
*
* Either string or format.pos must contain "%v" (value) to be valid
*/
function checkCurrencyFormat(format) {
var defaults = lib.settings.currency.format;
// Allow function as format parameter (should return string or object):
if ( typeof format === "function" ) format = format();
// Format can be a string, in which case `value` ("%v") must be present:
if ( isString( format ) && format.match("%v") ) {
// Create and return positive, negative and zero formats:
return {
pos : format,
neg : format.replace("-", "").replace("%v", "-%v"),
zero : format
};
// If no format, or object is missing valid positive value, use defaults:
} else if ( !format || !format.pos || !format.pos.match("%v") ) {
// If defaults is a string, casts it to an object for faster checking next time:
return ( !isString( defaults ) ) ? defaults : lib.settings.currency.format = {
pos : defaults,
neg : defaults.replace("%v", "-%v"),
zero : defaults
};
}
// Otherwise, assume format was fine:
return format;
}
/* --- API 方法--- */
/**
* 取得字串/字串數組,刪除所有格式/字串並傳回原始浮點值
* 別名:accounting.`parse(string)`
*
* 小數必須包含在符合浮點數的正規表示式(預設為
*accounting.settings.number.decimal),因此如果數字使用非標準小數
* 分隔符,請將其作為第二個參數提供。
*
* 也符合括號內的負數(例如「$ (1.99)」 => -1.99)
*
* 不會拋出任何錯誤(`NaN` 變成0),但這將來可能會改變
*/
var unformat = lib.unformat = lib.parse = function(value,decimal) {
// 遞歸地取消陣列格式:
if (isArray(value)) {
return map(value, function(val) {
return unformat(val,decimal);
});
}
// 無提示地失敗(需要適當的錯誤):
value = value || 0;
// 如果該值已經是數字,則按原樣傳回:
if (typeof value === "number") return value;
// 預設小數點來自設置,但可以設定為例如。 opts 中的「,」:
小數= 小數|| lib.settings.number.decimal;
// 建立正規表示式以去除數字、小數點和減號之外的所有內容:
var regex = new RegExp("[^0-9-" 小數"]", ["g"]),
unformatted = parseFloat(
("" value)
.replace(/(( .*))/, "-$1") // 用負數取代括號內的值
.replace(regex, ' ') // 去掉任何多餘的內容
.replace(decimal, '.') // 確保小數點是標準的
);
// 這會默默失敗,可能會造成麻煩,讓我們拭目以待:
return !isNaN(unformatted) ?未格式化:0;
};
/**
* toFixed() 的實現,將浮點數更像小數處理
*
* 修正了呈現
的二進位舍入問題(例如(0.615).toFixed(2) === " 0.61") * 會計和財務相關軟體的問題。
*/
var toFixed = lib.toFixed = function(value, precision) {
precision = checkPrecision( precision, lib.settings.number. precision); >var power = Math.pow(10, precision);
// 乘以精度,精確舍入,然後除以使用原生toFixed():
return (Math.round(lib.unformat(value) * power) / power).toFixed( precision);
};
/**
* 格式化數字,使用逗號分隔的千位和自訂精度/小數位
*
* 透過覆蓋精度和千位/小數分隔符號進行本地化
* 第二個參數` precision` 可以是一個物件匹配`settings.number`
*/
var formatNumber = lib.formatNumber = function(number, precision, Hundred, Decimal) {
// 遞歸格式化數組:
if (isArray(number) ) {
返回映射(數字, 函數(val) {
返回格式數字(val, 精度, 千位, 小數);
});
}
// 清理數字:
number = unformat(number);
// 從第二個參數(如果是對象)或所有參數建立選項對象,擴充預設值:
var opts = defaults(
(isObject( precision) ? precision : {
precision : precision,
thousand : 千,
decimal : 小數lib.settings.number
),
// 清理精度
usePrecision = checkPrecision(opts. precision) ,
// 進行一些計算:
負數= number base = parseInt(toFixed(Math.abs(number || 0), usePrecision), 10) "",
mod = base.length >; 3?鹼基長度% 3 : 0;
// 格式化數字:
回傳負數(mod ? base.substr(0, mod) opts.thousand : "") base.substr(mod).replace(/ (d{3})(? =d)/g, "$1" opts.thousand) (usePrecision ? opts.decimal toFixed(Math.abs(number), usePrecision).split('.')[1] : " ");
};
/**
* 將數字格式化為貨幣
*
* 用法:accounting.formatMoney(number, symbol, precision, HundredsSep, DecimalSep, format)
* 預設值:(0, "$", DecimalSep, format)
* 預設值:(0, "$", DecimalSep, format)
* 預設值:(0, "$", DecimalSep, format)
* 預設值:(0, "$", DecimalSep, format)
* 預設值:(0, "$", 2, ",", ".", "%s%v")
*
* 透過覆蓋符號、精確度、千位/小數分隔符號和格式進行本地化
* 第二個參數可以是與`settings 相符的物件.currency` 這是最簡單的方法。
*
* 待辦事項:整理參數
*/
var formatMoney = lib.formatMoney = function(number, symbol, precision, Hundred, Decimal, format) {
// 遞歸格式化數組:
if ( isArray(number)) {
返回映射(number, function(val){
返回formatMoney(val, 符號, 精度, 千位, 小數, 格式);
});
}
// 清理數字:
number = unformat(number);
// 從第二個參數(如果是對象)或所有參數建立選項對象,擴展默認值:
var opts = defaults(
(isObject(symbol) ? symbol : {
symbol : symbol,
精度:精度,
千:千,
小數以千計,小數, 格式:格式}),
lib.settings.currency
),
// 檢查格式(傳回帶有pos、neg 和零的物件):
formats = checkCurrencyFormat(opts.format),
//選擇該值使用的格式:
useFormat = number > 0 ? format.pos : 數字// 新增貨幣符號回傳:
return useFormat. replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(number), checkPrecision(opts. precision) ), opts.thousand, opts.decimal));
} ;
/**
* 將數字清單格式化為會計列,並用空格填滿
* 排列貨幣符號、千位分隔符號和小數位
*
* 清單應該是數字陣列
*個參數可以是包含與參數相符的鍵的物件
*
* 傳回相同長度的會計格式數字字串陣列
*
* 注意: `white-space:pre` CSS清單容器上需要規則,以防止
* 瀏覽器折疊輸出字串中的空格。
*/
lib.formatColumn = function(list, 符號, 精確度, 千位元, 小數, 格式) {
if (!list) return [];
// 從第二個參數(如果是對象)或所有參數建立選項對象,擴展預設值:
var opts = defaults(
(isObject(symbol) ? symbol : {
symbol : symbol,
precision : 精確度,
thousand : 千,
decimal : 小數,
format : 格式
}),
lib.settings.currency
),
/檢查格式(傳回帶有pos、neg 和0 的物件),目前只需要pos:
formats = checkCurrencyFormat(opts.format),
// 是否在字串開頭或貨幣符號之後填入:
padAfterSymbol =formats.pos.indexOf("%s") // 儲存列中最長字串的長度值:
maxLength = 0,
// 根據選項格式化列表,儲存最長字串的長度:
formatted = map(list, function(val, i) {
if (isArray(val)) {
// 若list 是多維數組,則遞歸格式化列:
return lib.formatColumn (val, opts);
} else {
// 清理值
val = unformat (val)
// 選擇該值所使用的格式(正、負或零) ):
var useFormat = val > 0 ?formats.pos : val //格式化該值,推入格式化清單並儲存長度:
fVal = useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(val), checkPrecision (opts. precision), opts.thousand, opts.decimal));
if (fVal.length > maxLength) maxLength = fVal.length;
回傳fVal;
}
}); 🎜>// 填滿清單中的每個數字並傳回數字欄位:
return map(formatted, function(val, i) {
// 僅當這是字串(不是嵌套陣列) ,已經被填滿):
if (isString(val) && val.length // 根據符號位置,在符號之後或索引0 處填充:
return padAfterSymbol val.replace( opts.symbol, opts.symbol (new Array(maxLength - val.length 1).join(" "))) : (new Array(maxLength - val.length 1).join(" ")) 值;
}
回傳val
});
};
/* --- 模組定義--- */
// CommonJS 的匯出記帳。如果作為 AMD 模組加載,請這樣定義。
// 否則,只需將`accounting` 新增至全域物件
if (typeof Exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = lib;
}
exports.accounting = lib;
} else if (typeof define === 'function' && Define.amd) {
/ / 將函式庫當作AMD 模組傳回:
define([], function() {
return函式庫
});
} else {
// 使用accounting.noConflict 將`accounting`恢復為其原始值。
// 傳回對庫的`accounting` 物件的參考;
// 例如`var Numbers = Accounting.noConflict();`
lib.noConflict = (function(oldAccounting) {
return function() {
// 重設根的`accounting` 變數的值:
root.accounting = oldAccounting;
// 刪除noConflict 方法:
lib.noConflict = undefined; // 傳回對函式庫的參考以重新指派它:
return lib; >};
})(root.accounting);
// 在根(全域/視窗)物件上宣告`fx` :
root['accounting'] = lib;
}
// 根目錄將是瀏覽器中的`window` 或伺服器上的`global`:
}(this));


官方下載位址:https://raw.github.com/josscrowcroft/accounting.js/master/accounting.js
使用實例
formatMoney



複製程式碼程式碼如下:

formatMoney
// 預設用法:
accounting.formatMoney(12345678); // $12,345,678.00
// 歐洲格式(自訂符號和分隔符號第二個參數:
accounting.formatMoney(4999.99, "?", 2, ".", ","); // ?4.999,99
// 負值的格式也很好:
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000
// 簡單的`format` 字串允許控制符號位置[%v = value, %s = symbol]:
accounting.formatMoney(5318008, { symbol: "GBP", format: “%v %s”}); // 5,318,008.00 GBP

formatNumber
>
複製程式碼


程式碼如下:

accounting.formatNumber(5318008); // 5,318,008
accounting.formatNumber( ); // 9 876 543.210 複製程式碼


複製程式碼

複製程式碼
複製程式碼複製碼> accounting.unformat("£ 12,345,678.90 英鎊"); // 12345678.9 官方示範實例:http://josscrowcroft. /腳本之家下載地址會計.js
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
使用Next.js(後端集成)構建多租戶SaaS應用程序使用Next.js(後端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:23 AM

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

如何使用Next.js(前端集成)構建多租戶SaaS應用程序如何使用Next.js(前端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:22 AM

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript:探索網絡語言的多功能性JavaScript:探索網絡語言的多功能性Apr 11, 2025 am 12:01 AM

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

JavaScript的演變:當前的趨勢和未來前景JavaScript的演變:當前的趨勢和未來前景Apr 10, 2025 am 09:33 AM

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

神秘的JavaScript:它的作用以及為什麼重要神秘的JavaScript:它的作用以及為什麼重要Apr 09, 2025 am 12:07 AM

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python還是JavaScript更好?Python還是JavaScript更好?Apr 06, 2025 am 12:14 AM

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

如何安裝JavaScript?如何安裝JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript不需要安裝,因為它已內置於現代瀏覽器中。你只需文本編輯器和瀏覽器即可開始使用。 1)在瀏覽器環境中,通過標籤嵌入HTML文件中運行。 2)在Node.js環境中,下載並安裝Node.js後,通過命令行運行JavaScript文件。

在Quartz中如何在任務開始前發送通知?在Quartz中如何在任務開始前發送通知?Apr 04, 2025 pm 09:24 PM

如何在Quartz中提前發送任務通知在使用Quartz定時器進行任務調度時,任務的執行時間是由cron表達式設定的。現�...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器