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

feat: added isolateDecimal #270

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions maths/decimal_isolation.ts
Original file line number Diff line number Diff line change
@@ -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)) }
}
16 changes: 16 additions & 0 deletions maths/test/decimal_isolation.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})