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
20 changes: 14 additions & 6 deletions accounting.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,13 +194,21 @@
decimal = decimal || lib.settings.number.decimal;

// Build regex to strip out everything except digits, decimal point and minus sign:
var regex = new RegExp("[^0-9-" + decimal + "]", ["g"]),
unformatted = parseFloat(
var regex = new RegExp("[^0-9-(-)-" + decimal + "]", ["g"]),
unformattedValueString =
("" + value)
.replace(/\((.*)\)/, "-$1") // replace bracketed values with negatives
.replace(regex, '') // strip out any cruft
.replace(decimal, '.') // make sure decimal point is standard
);
.replace(regex, '') // strip out any cruft
.replace(/\(([-]*\d*[^)]?\d+)\)/g, "-$1") // replace bracketed numeric values with negative, (100.1) = -100.1
.replace(/\((.*)\)/, '') // remove any brackets that do not have numeric value
.replace(decimal, '.'); // make sure decimal point is standard

/**
* Handling -ve number and bracket, eg.
* (-100) = 100, -(100) = 100, --100 = 100
*/
var negative = (unformattedValueString.match(/-/g) || 2).length % 2,
absUnformatted = parseFloat(unformattedValueString.replace(/-/g, '')),
unformatted = absUnformatted * ((negative) ? -1 : 1);

// This will fail silently which may cause trouble, let's wait and see:
return !isNaN(unformatted) ? unformatted : 0;
Expand Down
19 changes: 18 additions & 1 deletion tests/jasmine/core/unformatSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,24 @@ describe('unformat()', function(){
expect( accounting.unformat('&*()$ -123,456') ).toBe( -123456 );
expect( accounting.unformat(';$@#$%^&-123,456.78') ).toBe( -123456.78 );
});


it('should handle negative numbers and brackets', function(){
expect( accounting.unformat('(123,456)') ).toBe( -123456 );
expect( accounting.unformat('(123)456') ).toBe( -123456 );
expect( accounting.unformat('(IND)123') ).toBe( 123 );
expect( accounting.unformat('IND(123)') ).toBe( -123 );
expect( accounting.unformat('-(123)') ).toBe( 123 );
expect( accounting.unformat('(-123)') ).toBe( 123 );
expect( accounting.unformat('(1,234.56)') ).toBe( -1234.56 );
});

it('should handle negative deciaml numbers within brackets', function(){
expect( accounting.settings.number.deciaml = '@';
accounting.unformat('(1,234@56)') ).toBe( -1234.56 );
expect( accounting.settings.number.deciaml = '@';
accounting.unformat('(1,234.56)') ).toBe( -123456 );
});

it('should accept different decimal separators', function(){
expect( accounting.unformat('$ 123,456', ',') ).toBe( 123.456 );
expect( accounting.unformat('$ 123456|78', '|') ).toBe( 123456.78 );
Expand Down