public static roundTo(numberValue: number, scale: number): number {
const roundPower = Math.pow(10, scale);
- return Math.round(numberValue * roundPower) / roundPower;
- }
-
- public static truncTo(numberValue: number, scale: number): number {
- const truncPower = Math.pow(10, scale);
- return Math.trunc(numberValue * truncPower) / truncPower;
+ return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower;
}
public static getRandomFloatRounded(max = Number.MAX_VALUE, min = 0, scale = 2): number {
expect(randomInteger).toBeLessThanOrEqual(Math.floor(max));
});
+ it('Verify roundTo()', () => {
+ expect(Utils.roundTo(0, 2)).toBe(0);
+ expect(Utils.roundTo(0.5, 0)).toBe(1);
+ expect(Utils.roundTo(0.5, 2)).toBe(0.5);
+ expect(Utils.roundTo(-0.5, 0)).toBe(-1);
+ expect(Utils.roundTo(-0.5, 2)).toBe(-0.5);
+ expect(Utils.roundTo(1.005, 0)).toBe(1);
+ expect(Utils.roundTo(1.005, 2)).toBe(1.01);
+ expect(Utils.roundTo(2.175, 2)).toBe(2.18);
+ expect(Utils.roundTo(5.015, 2)).toBe(5.02);
+ expect(Utils.roundTo(-1.005, 2)).toBe(-1.01);
+ expect(Utils.roundTo(-2.175, 2)).toBe(-2.18);
+ expect(Utils.roundTo(-5.015, 2)).toBe(-5.02);
+ });
+
it('Verify getRandomFloat()', () => {
let randomFloat = Utils.getRandomFloat();
expect(typeof randomFloat === 'number').toBe(true);