Permalink
Browse files

Fixed toNumber with funny strings as an argument

Closes #157
  • Loading branch information...
1 parent 3ca1faa commit 146f72ff0509d485c664c08ddbd214dff22d90a0 @rwz rwz committed Nov 22, 2012
Showing with 9 additions and 5 deletions.
  1. +4 −4 lib/underscore.string.js
  2. +5 −1 test/strings.js
@@ -445,10 +445,10 @@
},
toNumber: function(str, decimals) {
- if (str == null || str == '') return 0;
- str = String(str);
- var num = parseNumber(parseNumber(str).toFixed(~~decimals));
- return num === 0 && !str.match(/^0+$/) ? Number.NaN : num;
+ if (!str) return 0;
+ str = _s.trim(str);
+ if (!str.match(/^-?\d+(?:\.\d+)?$/)) return NaN;
+ return parseNumber(parseNumber(str).toFixed(~~decimals));
},
numberFormat : function(number, dec, dsep, tsep) {
View
@@ -478,9 +478,13 @@ $(document).ready(function() {
});
test('String: toNumber', function() {
- deepEqual(_('not a number').toNumber(), Number.NaN);
+ deepEqual(_('not a number').toNumber(), NaN);
equal(_(0).toNumber(), 0);
equal(_('0').toNumber(), 0);
+ equal(_('0.0').toNumber(), 0);
+ equal(_('0.1').toNumber(), 0);
+ equal(_('0.1').toNumber(1), 0.1);
+ equal(_(' 0.1 ').toNumber(1), 0.1);
equal(_('0000').toNumber(), 0);
equal(_('2.345').toNumber(), 2);
equal(_('2.345').toNumber(NaN), 2);

0 comments on commit 146f72f

Please sign in to comment.