Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(number): improve float generation for precisions of form 10^-n #2581

Merged
merged 10 commits into from
Dec 27, 2023
5 changes: 3 additions & 2 deletions src/modules/number/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,9 @@ export class NumberModule extends SimpleModuleBase {
throw new FakerError(`Precision should be greater than 0.`);
}

const factor = Number.isInteger(Math.log10(precision))
? Math.pow(10, -Math.log10(precision)) //mathematically this is the same as 1/precision, however it helpfully gives integer values for all precisions of the form 10^-n
const logPrecision = Math.log10(precision);
const factor = Number.isInteger(logPrecision)
? Math.pow(10, -logPrecision) //mathematically this is the same as 1/precision, however it helpfully gives integer values for all precisions of the form 10^-n
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
: 1 / precision;
const int = this.int({
min: min * factor,
Expand Down
29 changes: 10 additions & 19 deletions test/modules/number.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,25 +275,16 @@ describe('number', () => {
expect(results).toEqual([0, 0.2, 0.4]);
});

it('provides numbers with an exact precision', () => {
for (let i = 0; i < 100; i++) {
const actual = faker.number.float({
min: 0.5,
max: 0.99,
precision: 0.01,
});
expect(actual).toBe(Number(actual.toFixed(2)));
}
});

it('provides numbers with an exact precision of 0.00001', () => {
for (let i = 0; i < 100; i++) {
const actual = faker.number.float({
min: 0.5,
max: 0.99,
precision: 0.00001,
});
expect(actual).toBe(Number(actual.toFixed(5)));
it('provides numbers with an exact precision of 10^-x for x=1 to 18', () => {
for (let factor = 1; factor <= 18; factor++) {
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
for (let i = 0; i < 100; i++) {
const actual = faker.number.float({
min: 0.5,
max: 0.99,
precision: Math.pow(10, -factor),
});
expect(actual).toBe(Number(actual.toFixed(factor)));
}
}
});

Expand Down