Skip to content

Precision

Returns a number with a fixed precision.

๐ŸŽฌ Usage

<script>
    import {precision} from "@sveu/shared/math"

    let number = 45.125

    const result = precision(number, 2)
</script>

<h1>{result}</h1>

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

๐Ÿ‘ป Arguments

Name Description Type Required
value The number to be precision number yes
digits The number of digits to be precision number yes

๐Ÿ™ˆ Options

Name Description Type Default
math Method to use for rounding, floor or ceil or round "floor" | "ceil" | "round" round

โ†ฉ๏ธ Returns

Precision number.

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
import { PrecisionOptions } from "../../utils"

/**
 * Set the precision of a number.
 *
 * @param value - The value to set the precision of
 *
 * @param digits - The number of digits to keep
 *
 * @param options - The options to use
 * - `math` - Method to use for rounding, floor or ceil or round (default: "round")
 *
 */
export function precision(
    value: number,
    digits: number,
    options?: PrecisionOptions
): number | string {
    const power = 10 ** digits
    return Math[options?.math || "round"](value * power) / power
}

Last update: 2023-02-14