Skip to content

Commit

Permalink
Fix generation of float numbers
Browse files Browse the repository at this point in the history
Fixes #401
  • Loading branch information
IvanGoncharov committed Feb 28, 2017
1 parent f379057 commit 38d2f34
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/random.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ function Random (faker, seed) {
max += options.precision;
}

var randomNumber = options.precision * Math.floor(
var randomNumber = Math.floor(
mersenne.rand(max / options.precision, options.min / options.precision));
// Workaround problem in Float point arithmetics for e.g. 6681493 / 0.01
randomNumber = randomNumber / (1 / options.precision);

return randomNumber;

Expand Down
8 changes: 8 additions & 0 deletions test/random.unit.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ describe("random.js", function () {

});

it("provides numbers with a with exact precision", function() {
var options = { min: 0.5, max: 0.99, precision: 0.01 };
for(var i = 0; i < 100; i++) {
var number = faker.random.number(options);
assert.equal(number, Number(number.toFixed(2)));
}
});

it("should not modify the input object", function() {
var min = 1;
var max = 2;
Expand Down

0 comments on commit 38d2f34

Please sign in to comment.