Skip to content

Commit

Permalink
require the number to be finite, and not in scientific notation if it…
Browse files Browse the repository at this point in the history
…'s non-integer, #109
  • Loading branch information
pixelzoom committed Aug 17, 2021
1 parent 6a11351 commit 90df01f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
4 changes: 3 additions & 1 deletion js/Utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -823,14 +823,16 @@ const Utils = {

/**
* Determines the number of decimal places in a value.
* @param {number} value
* @param {number} value - a finite number, scientific notation is not supported for decimal numbers
* @returns {number}
*/
numberOfDecimalPlaces( value ) {
assert && assert( typeof value === 'number' && isFinite( value ), `value must be a finite number ${value}` );
if ( Math.floor( value ) === value ) {
return 0;
}
else {
assert && assert( !value.toString().includes( 'e' ), `scientific notation is not supported: ${value}` );
return value.toString().split( '.' )[ 1 ].length;
}
},
Expand Down
14 changes: 14 additions & 0 deletions js/UtilsTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,8 @@ QUnit.test( 'toDegrees', assert => {
} );

QUnit.test( 'numberOfDecimalPlaces', assert => {

// Tests that should succeed.
assert.equal( Utils.numberOfDecimalPlaces( 10 ), 0 );
assert.equal( Utils.numberOfDecimalPlaces( -10 ), 0 );
assert.equal( Utils.numberOfDecimalPlaces( 10.1 ), 1 );
Expand All @@ -172,6 +174,18 @@ QUnit.test( 'numberOfDecimalPlaces', assert => {
assert.equal( Utils.numberOfDecimalPlaces( 0.001 ), 3 );
assert.equal( Utils.numberOfDecimalPlaces( -0.001 ), 3 );
assert.equal( Utils.numberOfDecimalPlaces( 0.56 ), 2 );
assert.equal( Utils.numberOfDecimalPlaces( 1e50 ), 0 ); // scientific notation is supported for integers

// Tests that should fail.
window.assert && assert.throws( () => {
Utils.numberOfDecimalPlaces( 'foo' );
}, 'value must be a number' );
window.assert && assert.throws( () => {
Utils.numberOfDecimalPlaces( Infinity );
}, 'value must be a finite number' );
window.assert && assert.throws( () => {
Utils.numberOfDecimalPlaces( 1e-50 );
}, 'scientific notation is not supported for decimals' );
} );

QUnit.test( 'roundToInterval', assert => {
Expand Down

0 comments on commit 90df01f

Please sign in to comment.