diff --git a/maths/decimal_isolation.ts b/maths/decimal_isolation.ts new file mode 100644 index 00000000..b25faabb --- /dev/null +++ b/maths/decimal_isolation.ts @@ -0,0 +1,23 @@ +/** + * @function isolateDecimal + * @description Isolate the decimal part of a number. + * @param {number} num - The number to isolate the decimal part from. + * @returns {Object} - Object containing the integral part and the decimal part. + * @throws {TypeError} - when the input is not a number. + * @example isolateDecimal(3.14) => { integralPart: 3, decimalPart: 0.14 } + */ + +export const isolateDecimal = ( + num: number +): { integralPart: number; decimalPart: number } => { + if (typeof num !== 'number') { + throw new TypeError('Input must be a number') + } + + num = Math.abs(num) + + const integralPart = Math.trunc(num) + const decimalPart = num - integralPart + + return { integralPart, decimalPart: Number(decimalPart.toFixed(10)) } +} diff --git a/maths/test/decimal_isolation.test.ts b/maths/test/decimal_isolation.test.ts new file mode 100644 index 00000000..0c4d24aa --- /dev/null +++ b/maths/test/decimal_isolation.test.ts @@ -0,0 +1,16 @@ +import { isolateDecimal } from '../decimal_isolation' + +describe('isolateDecimal', () => { + test('isolate the decimal part of a number', () => { + expect(isolateDecimal(3.14)).toEqual({ integralPart: 3, decimalPart: 0.14 }) + expect(isolateDecimal(0.14)).toEqual({ integralPart: 0, decimalPart: 0.14 }) + expect(isolateDecimal(-3.14)).toEqual({ + integralPart: 3, + decimalPart: 0.14 + }) + }) + + test('throws an error when the input is not a number', () => { + expect(() => isolateDecimal('3.14' as unknown as number)).toThrow(TypeError) + }) +})
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: