---
title: "clamp"
description: "Restrict a number to a closed interval, automatically swapping the bounds when they are passed in reverse order."
canonical_url: "https://core.mhaibaraai.cn/en/docs/utilities/math/clamp"
---
# clamp

> Restrict a number to a closed interval, automatically swapping the bounds when they are passed in reverse order.

## Usage

`clamp` restricts a number to the closed interval `[min, max]`, returning the nearest bound when the value falls outside it.

```ts
import { clamp } from '@movk/core'

clamp(5, 0, 10) // 5
clamp(15, 0, 10) // 10
clamp(-5, 0, 10) // 0
```

### Bounds Swap Automatically

When `min` is greater than `max`, the bounds are silently swapped, so callers do not have to normalize the argument order. This is also what allows [`mapRange`](https://core.mhaibaraai.cn/en/docs/utilities/math/map-range) to accept a reversed output range.

```ts
clamp(15, 10, 0) // 10
clamp(-5, 10, 0) // 0
```

### Edge Cases

```ts
clamp(5, 3, 3) // 3 (interval collapsed to a point)
clamp(1e10, 0, Number.POSITIVE_INFINITY) // 1e10
clamp(Number.NaN, 0, 10) // NaN
```

## API

### `clamp(value, min, max)`

Restrict a number to a closed interval.

### Parameters

**value** (`number`) *required*: The number to clamp.

**min** (`number`) *required*: One bound of the interval.

**max** (`number`) *required*: The other bound of the interval.

### Returns

**returns** (`number`): The value constrained to the interval. Returns NaN when value is NaN.

## Changelog

See commit history for [src/utilities/math/clamp.ts](https://github.com/mhaibaraai/movk-core/commits/main/src/utilities/math/clamp.ts).

---

- [GitHub](https://github.com/mhaibaraai/movk-core/blob/main/src/utilities/math/clamp.ts)


## Sitemap

See the full [sitemap](https://core.mhaibaraai.cn/sitemap.md) for all pages.
