According to the ECMAScript specification, Javascript values correspond to the IEEE 754 double-precision value of 64-bit binary format.
For the WebIDL validator I'm working on now, I need to find out if a given numeric value can be converted to a WebIDL float , that is, if it can be represented as a final single-point 32-bit IEEE 754 value.
Currently, I decided to use the following approach:
validate: function(value) {
if (typeof value !== 'number' || !Number.isFinite(value)) {
return false;
}
if (value === 0) {
return true;
}
var view = new DataView(new ArrayBuffer(4));
view.setFloat32(0, value);
var converted = view.getFloat32(0);
var relativeError = Math.abs(value - converted) / value;
return relativeError < Number.EPSILON;
}
In essence, I am doing this:
:
, ? ? , ?
, . , 1.001, 3.14159 .. , epsilon epsilon 32- (2 -23) , 16777217.
, , (2 24 - (2 24)).
validate: function(value) {
return typeof value === 'number' && Number.isFinite(value)
&& value >= -16777216 && value <= 16777216;
}