Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 51 additions & 17 deletions accounting.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,15 @@
decimal : ".", // decimal point separator
thousand : ",", // thousands separator
precision : 2, // decimal places
grouping : 3 // digit grouping (not implemented yet)
grouping : 3, // digit grouping (not implemented yet)
rounding_type: "default" // default rounding type is round up e.g. 0.5 is rounded to 1
},
number: {
precision : 0, // default precision on numbers is 0
grouping : 3, // digit grouping (not implemented yet)
thousand : ",",
decimal : "."
decimal : ".",
rounding_type: "default"
}
};

Expand Down Expand Up @@ -161,6 +163,26 @@
return format;
}

/**
* Gaussian or banker's rounding rounds 0.5 to 0, i.e. the closest even number
* This type of rounding is unbiased and results in more precise average
* Add rounding_type: 'gaussian' in settings to set it as default rounding
*/
function gaussianRound(value, precision, power) {
// Avoid rounding errors:
var val = (lib.unformat(value) * power).toFixed(8);

// i = integer part, f = fractional part, e = allow for rounding errors in f:
var i = Math.floor(val), f = val - i;
var e = 1e-8;

// Round to even, if fractional part is close to 0.5, else default round:
var r = (f > 0.5 - e && f < 0.5 + e) ?
((i % 2 == 0) ? i : i + 1) : Math.round(val);
return (r / power).toFixed(precision);;
};



/* --- API Methods --- */

Expand Down Expand Up @@ -212,28 +234,37 @@
*
* Fixes binary rounding issues (eg. (0.615).toFixed(2) === "0.61") that present
* problems for accounting- and finance-related software.
*
* Gaussian or banker's rounding, which is commonly used in banks, can be selected
* as 'rounding_type'
*/
var toFixed = lib.toFixed = function(value, precision) {
var toFixed = lib.toFixed = function(value, precision, rounding_type) {
precision = checkPrecision(precision, lib.settings.number.precision);
rounding_type = isString(rounding_type) ? rounding_type : lib.settings.number.rounding_type
var power = Math.pow(10, precision);

// Gaussian or banker's rounding:
if(rounding_type == "gaussian") {
return gaussianRound(value, precision, power);
}
// Default: round up .5
// Multiply up by precision, round accurately, then divide and use native toFixed():
return (Math.round(lib.unformat(value) * power) / power).toFixed(precision);
};


/**
* Format a number, with comma-separated thousands and custom precision/decimal places
* Alias: `accounting.format()`
*
* Localise by overriding the precision and thousand / decimal separators
* 2nd parameter `precision` can be an object matching `settings.number`
*/
var formatNumber = lib.formatNumber = lib.format = function(number, precision, thousand, decimal) {
var formatNumber = lib.formatNumber = lib.format = function(number, precision, thousand, decimal, rounding_type) {

// Resursively format arrays:
if (isArray(number)) {
return map(number, function(val) {
return formatNumber(val, precision, thousand, decimal);
return formatNumber(val, precision, thousand, decimal, rounding_type);
});
}

Expand All @@ -245,7 +276,8 @@
(isObject(precision) ? precision : {
precision : precision,
thousand : thousand,
decimal : decimal
decimal : decimal,
rounding_type : rounding_type
}),
lib.settings.number
),
Expand All @@ -255,26 +287,26 @@

// Do some calc:
negative = number < 0 ? "-" : "",
base = parseInt(toFixed(Math.abs(number || 0), usePrecision), 10) + "",
base = parseInt(toFixed(Math.abs(number || 0), usePrecision, rounding_type), 10) + "",
mod = base.length > 3 ? base.length % 3 : 0;

// Format the number:
return negative + (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] : "");
return negative + (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, rounding_type).split('.')[1] : "");
};


/**
* Format a number into currency
*
* Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format)
* defaults: (0, "$", 2, ",", ".", "%s%v")
* Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format, roundingType)
* defaults: (0, "$", 2, ",", ".", "%s%v", "default")
*
* Localise by overriding the symbol, precision, thousand / decimal separators and format
* Second param can be an object matching `settings.currency` which is the easiest way.
*
* To do: tidy up the parameters
*/
var formatMoney = lib.formatMoney = function(number, symbol, precision, thousand, decimal, format) {
var formatMoney = lib.formatMoney = function(number, symbol, precision, thousand, decimal, format, rounding_type) {
// Resursively format arrays:
if (isArray(number)) {
return map(number, function(val){
Expand All @@ -292,7 +324,8 @@
precision : precision,
thousand : thousand,
decimal : decimal,
format : format
format : format,
rounding_type : rounding_type
}),
lib.settings.currency
),
Expand All @@ -304,7 +337,7 @@
useFormat = number > 0 ? formats.pos : number < 0 ? formats.neg : formats.zero;

// Return with currency symbol added:
return useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(number), checkPrecision(opts.precision), opts.thousand, opts.decimal));
return useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(number), checkPrecision(opts.precision), opts.thousand, opts.decimal, opts.rounding_type));
};


Expand All @@ -320,7 +353,7 @@
* NB: `white-space:pre` CSS rule is required on the list container to prevent
* browsers from collapsing the whitespace in the output strings.
*/
lib.formatColumn = function(list, symbol, precision, thousand, decimal, format) {
lib.formatColumn = function(list, symbol, precision, thousand, decimal, format, rounding_type) {
if (!list) return [];

// Build options object from second param (if object) or all params, extending defaults:
Expand All @@ -330,7 +363,8 @@
precision : precision,
thousand : thousand,
decimal : decimal,
format : format
format : format,
rounding_type : rounding_type
}),
lib.settings.currency
),
Expand All @@ -357,7 +391,7 @@
var useFormat = val > 0 ? formats.pos : val < 0 ? formats.neg : formats.zero,

// Format this value, push into formatted list and save the length:
fVal = useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(val), checkPrecision(opts.precision), opts.thousand, opts.decimal));
fVal = useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(val), checkPrecision(opts.precision), opts.thousand, opts.decimal, opts.rounding_type));

if (fVal.length > maxLength) maxLength = fVal.length;
return fVal;
Expand Down
2 changes: 1 addition & 1 deletion accounting.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 21 additions & 9 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -174,16 +174,20 @@ <h4><strong>accounting.settings</strong></h4>
<pre class="prettyprint lang-js">// Settings object that controls default parameters for library methods:
accounting.settings = {
currency: {
symbol : "$", // default currency symbol is '$'
symbol : "$", // default currency symbol is '$'
format: "%s%v", // controls output: %s = symbol, %v = value/number (can be object: see below)
decimal : ".", // decimal point separator
decimal : ".", // decimal point separator
thousand: ",", // thousands separator
precision : 2 // decimal places
precision : 2, // decimal places
rounding_type: "default"// default rounding rounds 1.05 to 1.1 ie. rounds up 5
// to higher number. "gaussian" rounding, rounds to closest
// even, ie. 1.05 rounds to 1.0; useful in banking operations
},
number: {
precision : 0, // default precision on numbers is 0
thousand: ",",
decimal : "."
decimal : ".",
rounding_type: "default"
}
}

Expand All @@ -207,7 +211,7 @@ <h4><strong>accounting.settings</strong></h4>
<h4><strong>accounting.formatMoney()</strong></h4>

<pre class="prettyprint lang-js">// Standard usage and parameters (returns string):
accounting.formatMoney(number<em>,[symbol = "$"],[precision = 2],[thousand = ","],[decimal = "."],[format = "%s%v"]</em>)
accounting.formatMoney(number<em>,[symbol = "$"],[precision = 2],[thousand = ","],[decimal = "."],[format = "%s%v"], [rounding_type = "default"]</em>)

// Second parameter can be an object:
accounting.formatMoney(number<em>, [options]</em>)
Expand All @@ -218,14 +222,19 @@ <h4><strong>accounting.formatMoney()</strong></h4>
decimal : ".",
thousand: ",",
precision : 2,
format: "%s%v"
format: "%s%v",
rounding_type: "default"
};

// Example usage:
accounting.formatMoney(12345678); // $12,345,678.00
accounting.formatMoney(4999.99, "&euro;", 2, ".", ","); // &euro;4.999,99
accounting.formatMoney(-500000, "&pound; ", 0); // &pound; -500,000

// Default vs Gaussian rounding:
accounting.formatMoney(1500.505); // $1,500.51
accounting.formatMoney(1500.505, null, null, null, null, null, "gaussian"); // $1,500.50

// Example usage with options object:
accounting.formatMoney(5318008, {
symbol: "GBP",
Expand All @@ -246,7 +255,7 @@ <h4><strong>accounting.formatMoney()</strong></h4>
<h4><strong>accounting.formatColumn()</strong></h4>

<pre class="prettyprint lang-js">// Standard usage and parameters (returns array):
accounting.formatColumn(list<em>, [symbol = "$"],[precision = 2],[thousand = ","],[decimal = "."],[format = "%s%v"]</em>)
accounting.formatColumn(list<em>, [symbol = "$"],[precision = 2],[thousand = ","],[decimal = "."],[format = "%s%v"], [rounding_type = "default"]</em>)

// Second parameter can be an object (see formatNumber for available options):
accounting.formatColumn(list, <em>[options]</em>)
Expand All @@ -263,14 +272,16 @@ <h4><strong>accounting.formatColumn()</strong></h4>
<h4><strong>accounting.formatNumber()</strong></h4>

<pre class="prettyprint lang-js">// Standard usage and parameters (returns string):
accounting.formatNumber(number<em>, [precision = 0], [thousand = ","], [decimal = "."]</em>)
accounting.formatNumber(number<em>, [precision = 0], [thousand = ","], [decimal = "."], [rounding_type = "default"]</em>)

// Second parameter can also be an object matching `settings.number`:
accounting.formatNumber(number<em>, [object]</em>)

// Example usage:
accounting.formatNumber(9876543); // 9,876,543
accounting.formatNumber(4999.99, 2, ".", ","); // 4.999,99
accounting.formatNumber(4999.505, 2, null, null, "gaussian"); // 4,999.50


// Example usage with options object:
accounting.formatNumber(5318008, {
Expand All @@ -285,10 +296,11 @@ <h4><strong>accounting.formatNumber()</strong></h4>
<h4><strong>accounting.toFixed()</strong></h4>

<pre class="prettyprint lang-js">// Standard usage and parameters (returns string):
accounting.toFixed(number<em>, [precision = 0]</em>);
accounting.toFixed(number<em>, [precision = 0], [rounding_type = "default"]</em>);

// Example usage:
accounting.toFixed(0.615, 2); // "0.62"
accounting.toFixed(0.605, 2, "gaussian"); // "0.60", default would round to "0.61"

// Compare to regular JavaScript `Number.toFixed()` method:
(0.615).toFixed(2); // "0.61"</pre>
Expand Down
2 changes: 1 addition & 1 deletion tests/jasmine/core/formatMoneySpec.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
describe('formatMoney()', function(){

it('should work for small numbers', function(){

expect( accounting.formatMoney(123) ).toBe( '$123.00' );
expect( accounting.formatMoney(123.45) ).toBe( '$123.45' );
expect( accounting.formatMoney(12345.67) ).toBe( '$12,345.67' );
Expand Down
6 changes: 6 additions & 0 deletions tests/jasmine/core/formatNumberSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,12 @@ describe('formatNumber', function(){
expect( accounting.formatNumber(98765432.12, 4, '[', ']') ).toBe( '98[765[432]1200' );
});

it('should allow setting gaussian rounding', function(){
expect( accounting.formatNumber(98765432.105, 2, null, null, "gaussian") ).toBe( '98,765,432.10' );
expect( accounting.formatNumber(98765432.115, 2, null, null, "gaussian") ).toBe( '98,765,432.12' );
expect( accounting.formatNumber(98765432.125, 2, null, null, "gaussian") ).toBe( '98,765,432.12' );
});

it('should use default separators if null', function(){
expect( accounting.formatNumber(12345.12345, 2, null, null) ).toBe('12,345.12');
});
Expand Down
11 changes: 11 additions & 0 deletions tests/jasmine/core/toFixedSpec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
describe('toFixed()', function(){

it('should allow setting gaussian round', function(){

expect( accounting.toFixed(123.505, 2, "gaussian") ).toBe( '123.50' );
expect( accounting.toFixed(123.525, 2, "gaussian") ).toBe( '123.52' );
expect( accounting.toFixed(123.515, 2, "gaussian") ).toBe( '123.52' );

});

});
1 change: 1 addition & 0 deletions tests/jasmine/runner.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<script src="core/formatNumberSpec.js"></script>
<script src="core/unformatSpec.js"></script>
<script src="core/formatMoneySpec.js"></script>
<script src="core/toFixedSpec.js"></script>
</head>
<body>
<script>
Expand Down
Loading