From 09b07fcc24c0a585a3bf6b25a634e37bf1d2d6ed Mon Sep 17 00:00:00 2001 From: Graeme Date: Sun, 30 Nov 2014 11:38:27 -0500 Subject: [PATCH 1/2] Fixes #329; Allow negative decimal precision --- test/strings.js | 25 +++++++++++++++++++++---- toNumber.js | 9 ++++----- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/test/strings.js b/test/strings.js index 461e2858..b6d147b7 100644 --- a/test/strings.js +++ b/test/strings.js @@ -602,10 +602,14 @@ $(document).ready(function() { }); test('String: toNumber', function() { - deepEqual(_('not a number').toNumber(), NaN); + _.each(['not a number', NaN, {}, [/a/], 'alpha6'], function(val) { + deepEqual(_('not a number').toNumber(), NaN); + equal(_(Math.PI).toNumber(val), 3); + }); equal(_(0).toNumber(), 0); equal(_('0').toNumber(), 0); equal(_('0.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); @@ -618,9 +622,22 @@ $(document).ready(function() { equal(_(2).toNumber(2), 2.00); equal(_(-2).toNumber(), -2); equal(_('-2').toNumber(), -2); - equal(_('').toNumber(), 0); - equal(_(null).toNumber(), 0); - equal(_(undefined).toNumber(), 0); + equal(_(-2.5123).toNumber(3), -2.512); + + // Negative precisions + equal(_(-234).toNumber(-1), -230); + equal(_(234).toNumber(-2), 200); + equal(_('234').toNumber(-2), 200); + + _.each(['', null, undefined], function(val) { + equal(_(val).toNumber(), 0); + }); + + _.each([Infinity, -Infinity], function(val) { + equal(_(val).toNumber(), val); + equal(_(val).toNumber(val), val); + equal(_(1).toNumber(val), 1); + }); }); test('String: numberFormat', function() { diff --git a/toNumber.js b/toNumber.js index 437c4316..75dc1dc3 100644 --- a/toNumber.js +++ b/toNumber.js @@ -3,9 +3,8 @@ var parseNumber = function(source) { return source * 1 || 0; }; -module.exports = function toNumber(str, decimals) { - if (!str) return 0; - str = trim(str); - if (!str.match(/^-?\d+(?:\.\d+)?$/)) return NaN; - return parseNumber(parseNumber(str).toFixed(~~decimals)); +module.exports = function toNumber(num, precision) { + if (num == null) return 0; + var factor = Math.pow(10, isFinite(precision) ? precision : 0); + return Math.round(num * factor) / factor; }; From 90ba86f305501744f4da8896a94851cef5c9ced5 Mon Sep 17 00:00:00 2001 From: Graeme Yeates Date: Tue, 23 Dec 2014 10:06:42 -0500 Subject: [PATCH 2/2] Provide an example for toNumber with negative values --- README.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.markdown b/README.markdown index a1b9526b..68b338e8 100644 --- a/README.markdown +++ b/README.markdown @@ -471,6 +471,9 @@ toNumber('2.556') toNumber('2.556', 1) // => 2.6 + +toNumber('999.999', -1) +// => 990 ``` #### strRight(string, pattern) => string