From b72b0d60cb0bebac3cce453fdb7c8a0b80f1a7c5 Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Sun, 12 May 2013 15:48:01 -0700 Subject: [PATCH] Add support for floating point numbers to `_.random`. [closes #263] Former-commit-id: ef356bb180b163fc936ef69ac2ef33186983eaa7 --- lodash.js | 7 ++++++- test/test.js | 9 +++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lodash.js b/lodash.js index 1329b3945..922174a77 100644 --- a/lodash.js +++ b/lodash.js @@ -4961,8 +4961,13 @@ if (max == null) { max = min; min = 0; + } else { + max = +max || 0; } - return min + floor(nativeRandom() * ((+max || 0) - min + 1)); + var rand = nativeRandom(); + return (min % 1 || max % 1) + ? min + nativeMin(rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1))), max) + : min + floor(rand * (max - min + 1)); } /** diff --git a/test/test.js b/test/test.js index 3f4518106..4be611790 100644 --- a/test/test.js +++ b/test/test.js @@ -2306,6 +2306,15 @@ test('should coerce arguments to numbers', function() { strictEqual(_.random('1', '1'), 1); }); + + test('should support floats', function() { + var min = 1.5, + max = 1.6, + actual = _.random(min, max); + + ok(actual % 1); + ok(actual >= min && actual <= max); + }); }()); /*--------------------------------------------------------------------------*/