Skip to content

Commit 2e8ea4a

Browse files
committed
feat(number): add margin util
1 parent c9e3a40 commit 2e8ea4a

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/number.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,3 +204,23 @@ export function convertPayRate(
204204
const newValue = hourlyValue * toHour[payRateUnit];
205205
return { value: parseFloat(newValue.toFixed(2)), unit: payRateUnit };
206206
}
207+
208+
/**
209+
* Calculates the margin percentage between a base value and an actual value.
210+
*
211+
* ```ts
212+
* margin(100, 150); // 50
213+
* margin(200, 100); // -50
214+
* margin(0, 100); // undefined (avoids division by zero)
215+
* margin(null, 100); // undefined
216+
* margin(100, null); // undefined
217+
* ```
218+
*
219+
* @param base Cost (or Base Value) – the original or maximum reference value (e.g. cost price, max rate).
220+
* @param actual Current or Actual Value – the value you compare against the base (e.g. selling price, current rate).
221+
*/
222+
export function margin(base: Maybe<number>, actual: Maybe<number>) {
223+
if (actual == null || base == null) return undefined;
224+
if (base === 0) return undefined;
225+
return ((actual - base) / base) * 100;
226+
}

0 commit comments

Comments
 (0)