From dbab2ec812da3e608f06ac7670a2bff958e78778 Mon Sep 17 00:00:00 2001 From: Nic <24358775+nicfv@users.noreply.github.com> Date: Tue, 5 Mar 2024 11:36:41 -0800 Subject: [PATCH] Add rounding function (#15) * Minor doc updates * Add contribution guidelines in readme * Update typedoc * Release v1.0.1 * Add rounding function * n cannot be infinity * Normalize bug * Changelog for v1.0.2 * Release v1.0.2 --- smath/CHANGELOG.md | 6 ++++++ smath/package.json | 2 +- smath/src/Polate.ts | 2 +- smath/src/SMath.ts | 15 ++++++++++++++- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/smath/CHANGELOG.md b/smath/CHANGELOG.md index 215d35b5..988ded9c 100644 --- a/smath/CHANGELOG.md +++ b/smath/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 1.0.2 + +- Add rounding function +- `isNumber` cannot be +/- infinity +- Fix normalization bug when `min = max` + ## 1.0.1 - Fix minor documentation in `SMath` diff --git a/smath/package.json b/smath/package.json index 9598493a..9658295b 100644 --- a/smath/package.json +++ b/smath/package.json @@ -1,6 +1,6 @@ { "name": "smath", - "version": "1.0.1", + "version": "1.0.2", "description": "Small math function library", "main": "dist/index.js", "types": "types/index.d.ts", diff --git a/smath/src/Polate.ts b/smath/src/Polate.ts index 5dd8750a..175b8a43 100644 --- a/smath/src/Polate.ts +++ b/smath/src/Polate.ts @@ -15,7 +15,7 @@ export abstract class Polate { */ public static normalize(n: number, min: number, max: number): number { if (min === max) { - return min; + return 0; } return (n - min) / (max - min); } diff --git a/smath/src/SMath.ts b/smath/src/SMath.ts index a7d0ec95..f5b510d1 100644 --- a/smath/src/SMath.ts +++ b/smath/src/SMath.ts @@ -13,7 +13,7 @@ export abstract class SMath { * ``` */ public static isNumber(n: any): boolean { - return typeof n === 'number'; + return typeof n === 'number' && n !== Infinity && n !== -Infinity; } /** * Clamp a number within a range. @@ -51,4 +51,17 @@ export abstract class SMath { public static approx(a: number, b: number, epsilon: number = 1e-6): boolean { return a - b < epsilon && b - a < epsilon; } + /** + * Round a number to any number of decimal places. + * @param n The number to round + * @param d The number of places on the right side of the decimal + * @returns The rounded number + * @example + * ```js + * const pi = SMath.round(3.1416, 2); // 3.14 + * ``` + */ + public static round(n: number, d: number): number { + return Math.round(n * 10 ** d) / (10 ** d); + } } \ No newline at end of file