Skip to content

Commit 16293bc

Browse files
committed
Merge branch 'feature/string-builder'
2 parents fa8be8c + 071fe87 commit 16293bc

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

MADE.Data.Converters/src/math/index.ts

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,35 @@
55
*/
66
export function toRadians(degrees: number): number {
77
return degrees * (Math.PI / 180);
8-
}
8+
}
9+
10+
/**
11+
* Rounds a value, towards zero, if the remainder of dividing number by multiple is greater than or equal to half the value of multiple.
12+
* @param {number} number - The value to round.
13+
* @param {number} multiple - The multiple to which you want to round number.
14+
* @return {number} The number rounded to the desired multiple.
15+
*/
16+
export function mRound(number: number, multiple: number): number {
17+
if (isNaN(multiple)) {
18+
return 0;
19+
}
20+
21+
multiple = Number(multiple);
22+
var result = number % multiple;
23+
if (result < 0) {
24+
return -mRound(-number, -multiple);
25+
}
26+
27+
result = Number((number - result).toFixed(0));
28+
var compare = (multiple / 2) <= Math.abs(number - result);
29+
if (compare) {
30+
if (result < 0) {
31+
result -= multiple;
32+
} else {
33+
result += multiple;
34+
}
35+
}
36+
37+
38+
return result;
39+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { mRound } from '../../src'
2+
3+
describe("when rounding to the nearest multiple", () => {
4+
test.each([
5+
[10, 3, 9],
6+
[-10, -3, -9],
7+
[1.3, 0.2, 1.2],
8+
])(
9+
"should round to the nearest multiple of the given number",
10+
(value, multiple, expected) => {
11+
expect(mRound(value, multiple)).toBe(expected)
12+
}
13+
)
14+
});

0 commit comments

Comments
 (0)