All files / math / round_to.ts

100.00% Branches 4/4
100.00% Lines 11/11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x3
x3
x3
x3
 
x16
x29
x29
 
x16
x16
x16
x16












































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * Options for {@linkcode roundTo}.
 */
export type RoundingOptions = {
  /**
   * The strategy to use for rounding.
   * @default {"round"}
   */
  strategy?: "round" | "floor" | "ceil" | "trunc";
};

/**
 * Round a number to a specified number of digits.
 *
 * @param num The number to be rounded
 * @param digits The number of digits to round to
 * @param options Options for rounding
 * @returns The rounded number
 *
 * @example Usage
 * ```ts
 * import { roundTo } from "@std/math/round-to";
 * import { assertEquals } from "@std/assert";
 * assertEquals(roundTo(Math.PI, 2), 3.14);
 * assertEquals(roundTo(Math.PI, 2, { strategy: "ceil" }), 3.15);
 * assertEquals(roundTo(Math.PI, 3), 3.142);
 * assertEquals(roundTo(Math.PI, 3, { strategy: "floor" }), 3.141);
 * assertEquals(roundTo(-Math.PI, 3, { strategy: "trunc" }), -3.141);
 * ```
 */
export function roundTo(
  num: number,
  digits: number,
  options?: RoundingOptions,
): number {
  if (!Number.isSafeInteger(digits) || digits < 0) {
    throw new RangeError("`digits` must be a non-negative integer");
  }

  const { strategy = "round" } = options ?? {};
  const factor = 10 ** digits;
  return Math[strategy](num * factor) / factor;
}