Add support for floating point numbers to _.random. [closes #263]

Former-commit-id: ef356bb180b163fc936ef69ac2ef33186983eaa7
This commit is contained in:
John-David Dalton
2013-05-12 15:48:01 -07:00
parent 5841e62c66
commit b72b0d60cb
2 changed files with 15 additions and 1 deletions

View File

@@ -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));
}
/**

View File

@@ -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);
});
}());
/*--------------------------------------------------------------------------*/