diff --git a/accounting.js b/accounting.js index 755a3d5..0f2e149 100644 --- a/accounting.js +++ b/accounting.js @@ -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; diff --git a/tests/jasmine/core/unformatSpec.js b/tests/jasmine/core/unformatSpec.js index 1f0f17e..b4991db 100644 --- a/tests/jasmine/core/unformatSpec.js +++ b/tests/jasmine/core/unformatSpec.js @@ -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 );