Add roundOffFloat
helper method
This commit is contained in:
parent
906eb7dc1c
commit
b487881494
2 changed files with 39 additions and 0 deletions
|
@ -541,6 +541,26 @@ export const addSelectOnFocusBehaviour = (selector = '.js-select-on-focus') => {
|
|||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Method to round of values with decimal places
|
||||
* with provided precision.
|
||||
*
|
||||
* Taken from https://stackoverflow.com/a/7343013/414749
|
||||
*
|
||||
* Eg; roundOffFloat(3.141592, 3) = 3.142
|
||||
*
|
||||
* Refer to spec/javascripts/lib/utils/common_utils_spec.js for
|
||||
* more supported examples.
|
||||
*
|
||||
* @param {Float} number
|
||||
* @param {Number} precision
|
||||
*/
|
||||
export const roundOffFloat = (number, precision = 0) => {
|
||||
// eslint-disable-next-line no-restricted-properties
|
||||
const multiplier = Math.pow(10, precision);
|
||||
return Math.round(number * multiplier) / multiplier;
|
||||
};
|
||||
|
||||
window.gl = window.gl || {};
|
||||
window.gl.utils = {
|
||||
...(window.gl.utils || {}),
|
||||
|
|
|
@ -627,4 +627,23 @@ describe('common_utils', () => {
|
|||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('roundOffFloat', () => {
|
||||
it('Rounds off decimal places of a float number with provided precision', () => {
|
||||
expect(commonUtils.roundOffFloat(3.141592, 3)).toBe(3.142);
|
||||
});
|
||||
|
||||
it('Rounds off a float number to a whole number when provided precision is zero', () => {
|
||||
expect(commonUtils.roundOffFloat(3.141592, 0)).toBe(3);
|
||||
expect(commonUtils.roundOffFloat(3.5, 0)).toBe(4);
|
||||
});
|
||||
|
||||
it('Rounds off float number to nearest 0, 10, 100, 1000 and so on when provided precision is below 0', () => {
|
||||
expect(commonUtils.roundOffFloat(34567.14159, -1)).toBe(34570);
|
||||
expect(commonUtils.roundOffFloat(34567.14159, -2)).toBe(34600);
|
||||
expect(commonUtils.roundOffFloat(34567.14159, -3)).toBe(35000);
|
||||
expect(commonUtils.roundOffFloat(34567.14159, -4)).toBe(30000);
|
||||
expect(commonUtils.roundOffFloat(34567.14159, -5)).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in a new issue