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

Avoid IEEE-754 issues for multipleOf and divisibleBy #228

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
59 changes: 30 additions & 29 deletions lib/attribute.js
Original file line number Diff line number Diff line change
Expand Up @@ -412,59 +412,60 @@ validators.maximum = function validateMaximum (instance, schema, options, ctx) {
};

/**
* Validates divisibleBy when the type of the instance value is a number.
* Of course, this is susceptible to floating point error since it compares the floating points
* and not the JSON byte sequences to arbitrary precision.
* Perform validation for multipleOf and divisibleBy, which are essentially the same.
* @param instance
* @param schema
* @return {String|null}
* @param validationType
* @param errorMessage
* @returns {String|null}
*/
validators.divisibleBy = function validateDivisibleBy (instance, schema, options, ctx) {
var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy (instance, schema, options, ctx, validationType, errorMessage) {
if (typeof instance !== 'number') {
return null;
}

if (schema.divisibleBy == 0) {
throw new SchemaError("divisibleBy cannot be zero");
var validationArgument = schema[validationType];
if (validationArgument == 0) {
throw new SchemaError(validationType + " cannot be zero");
}

var result = new ValidatorResult(instance, schema, options, ctx);
if (instance / schema.divisibleBy % 1) {

var instanceDecimals = helpers.getDecimalPlaces(instance);
var divisorDecimals = helpers.getDecimalPlaces(validationArgument);

var maxDecimals = Math.max(instanceDecimals , divisorDecimals);
var multiplier = Math.pow(10, maxDecimals);

if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) {
result.addError({
name: 'divisibleBy',
argument: schema.divisibleBy,
message: "is not divisible by (multiple of) " + JSON.stringify(schema.divisibleBy),
name: validationType,
argument: validationArgument,
message: errorMessage + JSON.stringify(validationArgument)
});
}

return result;
};

/**
* Validates divisibleBy when the type of the instance value is a number.
* Of course, this is susceptible to floating point error since it compares the floating points
* and not the JSON byte sequences to arbitrary precision.
* @param instance
* @param schema
* @return {String|null}
*/
validators.multipleOf = function validateMultipleOf (instance, schema, options, ctx) {
if (typeof instance !== 'number') {
return null;
}

if (schema.multipleOf == 0) {
throw new SchemaError("multipleOf cannot be zero");
}
return validateMultipleOfOrDivisbleBy(instance, schema, options, ctx, "multipleOf", "is not a multiple of (divisible by) ");
};

var result = new ValidatorResult(instance, schema, options, ctx);
if (instance / schema.multipleOf % 1) {
result.addError({
name: 'multipleOf',
argument: schema.multipleOf,
message: "is not a multiple of (divisible by) " + JSON.stringify(schema.multipleOf),
});
}
return result;
/**
* Validates multipleOf when the type of the instance value is a number.
* @param instance
* @param schema
* @return {String|null}
*/
validators.divisibleBy = function validateDivisibleBy (instance, schema, options, ctx) {
return validateMultipleOfOrDivisbleBy(instance, schema, options, ctx, "divisibleBy", "is not divisible by (multiple of) ");
};

/**
Expand Down
35 changes: 35 additions & 0 deletions lib/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -288,3 +288,38 @@ exports.encodePath = function encodePointer(a){
// the slash is encoded by encodeURIComponent
return a.map(pathEncoder).join('');
};


/**
* Calculate the number of decimal places a number uses
* We need this to get correct results out of multipleOf and divisibleBy
* when either figure is has decimal places, due to IEEE-754 float issues.
* @param number
* @returns {number}
*/
exports.getDecimalPlaces = function getDecimalPlaces(number) {

var decimalPlaces = 0;
if (isNaN(number)) return decimalPlaces;

if (typeof number !== 'number') {
number = Number(number);
}

var parts = number.toString().split('e');
if (parts.length === 2) {
if (parts[1][0] !== '-') {
return decimalPlaces;
} else {
decimalPlaces = Number(parts[1].slice(1));
}
}

var decimalParts = parts[0].split('.');
if (decimalParts.length === 2) {
decimalPlaces += decimalParts[1].length;
}

return decimalPlaces;
};

28 changes: 27 additions & 1 deletion test/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ describe('Attributes', function () {
});
});

describe('dividibleBy', function () {
describe('divisibleBy', function () {
beforeEach(function () {
this.validator = new Validator();
});
Expand All @@ -206,6 +206,32 @@ describe('Attributes', function () {
it('should not validate 1 is even', function () {
return this.validator.validate(1, {'type': 'number', 'divisibleBy': 2}).valid.should.be.false;
});

it('should validate divisibleBy with decimals', function () {
return this.validator.validate(2.4, {'type': 'number', 'divisibleBy': 0.1}).valid.should.be.true;
});
});

describe('multipleOf', function () {
beforeEach(function () {
this.validator = new Validator();
});

it('should validate if 0 is even', function () {
return this.validator.validate(2, {'type': 'number', 'multipleOf': 2}).valid.should.be.true;
});

it('should validate if -2 is even', function () {
return this.validator.validate(-2, {'type': 'number', 'multipleOf': 2}).valid.should.be.true;
});

it('should not validate 1 is even', function () {
return this.validator.validate(1, {'type': 'number', 'multipleOf': 2}).valid.should.be.false;
});

it('should validate mutlipleOf with decimals', function () {
return this.validator.validate(2.4, {'type': 'number', 'multipleOf': 0.1}).valid.should.be.true;
});
});

describe('pattern', function () {
Expand Down