diff --git a/accounting.js b/accounting.js index fd181fd..6c7d093 100644 --- a/accounting.js +++ b/accounting.js @@ -195,10 +195,16 @@ // Build regex to strip out everything except digits, decimal point and minus sign: var regex = new RegExp("[^0-9-" + decimal + "]", ["g"]), - unformatted = parseFloat( - ("" + value) + escapedDecimal = decimal.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'), + decimalRegex = new RegExp(escapedDecimal, 'g'), + strippedValue = ("" + value) .replace(/\((?=\d+)(.*)\)/, "-$1") // replace bracketed values with negatives - .replace(regex, '') // strip out any cruft + .replace(regex, ''), // strip out any cruft + decimalCount = (strippedValue.match(decimalRegex) || []).length, + unformatted = parseFloat( + (decimalCount > 1 ? strippedValue.replace(decimalRegex, function(match, offset, string) { + return offset === string.lastIndexOf(decimal) ? match : ''; + }) : strippedValue) .replace(decimal, '.') // make sure decimal point is standard ); diff --git a/tests/jasmine/core/unformatSpec.js b/tests/jasmine/core/unformatSpec.js index 7c6a093..12fb6c8 100644 --- a/tests/jasmine/core/unformatSpec.js +++ b/tests/jasmine/core/unformatSpec.js @@ -22,6 +22,10 @@ describe('unformat()', function(){ expect( accounting.unformat(';$@#$%^&123,456\'78', '\'') ).toBe( 123456.78 ); }); + it('should ignore extra decimal separators that come from the currency symbol', function(){ + expect( accounting.unformat('kr. 123.45', '.') ).toBe( 123.45 ); + }); + it('should accept an array', function(){ var vals = accounting.unformat(['$ 123', '$567.89', 'R$12,345,678.901']); expect( vals[0] ).toBe( 123 );