Skip to content

Commit

Permalink
fix(round): Throw an exception when precision is not an integer (#79)
Browse files Browse the repository at this point in the history
* feat: add exception when precision is integer

* test: add testcase for precision exception

* docs: add examples for exception
  • Loading branch information
westofsky authored Jun 20, 2024
1 parent cfc47e4 commit 92c9db0
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/ko/reference/math/round.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ function round(value: number, precision?: number): number;
const result1 = round(1.2345); // result1은 1이 되어요.
const result2 = round(1.2345, 2); // result2는 1.23이 되어요.
const result3 = round(1.2345, 3); // result3는 1.235가 되어요.
const result4 = round(1.2345, 3.1); // precision이 integer가 아니면 오류를 반환해요.
```
1 change: 1 addition & 0 deletions docs/reference/math/round.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@ function round(value: number, precision?: number): number;
const result1 = round(1.2345); // result1 will be 1
const result2 = round(1.2345, 2); // result2 will be 1.23
const result3 = round(1.2345, 3); // result3 will be 1.235
const result4 = round(1.2345, 3.1); // This will throw an error
```
8 changes: 8 additions & 0 deletions src/math/round.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,12 @@ describe('round function', () => {
it('works with precision leading to no rounding', () => {
expect(round(8.88888, 5)).toBe(8.88888);
});

it('handles edge cases where precision is not integer', () => {
const value = 1.2345;
const precision = 3.1;
expect(() => round(value, precision)).toThrow(
'Precision must be an integer.'
);
});
});
5 changes: 5 additions & 0 deletions src/math/round.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,18 @@
* @param {number} value - The number to round.
* @param {number} [precision=0] - The number of decimal places to round to. Defaults to 0.
* @returns {number} The rounded number.
* @throws {Error} Throws an error if `Precision` is not integer.
*
* @example
* const result1 = round(1.2345); // result1 will be 1
* const result2 = round(1.2345, 2); // result2 will be 1.23
* const result3 = round(1.2345, 3); // result3 will be 1.235
* const result4 = round(1.2345, 3.1); // This will throw an error
*/
export function round(value: number, precision = 0): number {
if (!Number.isInteger(precision)) {
throw new Error('Precision must be an integer.');
}
const multiplier = Math.pow(10, precision);
return Math.round(value * multiplier) / multiplier;
}

0 comments on commit 92c9db0

Please sign in to comment.