diff --git a/accounting.js b/accounting.js index 755a3d5..d313655 100644 --- a/accounting.js +++ b/accounting.js @@ -176,7 +176,9 @@ * * Doesn't throw any errors (`NaN`s become 0) but this may change in future */ - var unformat = lib.unformat = lib.parse = function(value, decimal) { + var unformat = lib.unformat = lib.parse = function(value, decimal, failure_result) { + if (failure_result === undefined) + failure_result = 0; // Recursively unformat arrays: if (isArray(value)) { return map(value, function(val) { @@ -203,7 +205,7 @@ ); // This will fail silently which may cause trouble, let's wait and see: - return !isNaN(unformatted) ? unformatted : 0; + return !isNaN(unformatted) ? unformatted : failure_result; }; diff --git a/index.html b/index.html index 2f3b3f4..2df0b14 100644 --- a/index.html +++ b/index.html @@ -297,14 +297,20 @@

accounting.toFixed()

accounting.unformat()

// Standard usage and parameters (returns number):
-accounting.unformat(string, [decimal]);
+accounting.unformat(string, [decimal], [failure_result]);
 
 // Example usage:
 accounting.unformat("GBP £ 12,345,678.90"); // 12345678.9
 
 // If a non-standard decimal separator was used (eg. a comma) unformat() will need it in order to work out
 // which part of the number is a decimal/float:
-accounting.unformat("€ 1.000.000,00", ","); // 1000000
+accounting.unformat("€ 1.000.000,00", ","); // 1000000 + +// if passed string is not a number convertible, unformat fails and return 0 +// you can specify failure_result response of your choice for flexibility and avoid ambiguity. +accounting.unformat("€ Not a Number", ","); // 0 +accounting.unformat("€ Not a Number", ",", "failed"); // "failed" + diff --git a/tests/qunit/methods.js b/tests/qunit/methods.js index 19e354b..0e679e9 100644 --- a/tests/qunit/methods.js +++ b/tests/qunit/methods.js @@ -7,6 +7,8 @@ $(document).ready(function() { equals(accounting.unformat(1234567890), 1234567890, 'Returns same value when passed an integer'); equals(accounting.unformat("string"), 0, 'Returns 0 for a string with no numbers'); equals(accounting.unformat({joss:1}), 0, 'Returns 0 for object'); + equals(accounting.unformat("string", ',', null), null, 'Returns user specified failure response for a string with no numbers'); + equals(accounting.unformat("string", ',', "failed"), "failed", 'Returns user specified failure response for a string with no numbers'); accounting.settings.number.decimal = ','; equals(accounting.unformat("100,00"), 100, 'Uses decimal separator from settings');