Files
30-seconds-of-code/snippets/js/s/to-safe-integer.md
Angelos Chalaris 4d0316a062 Update covers
2023-05-07 22:25:00 +03:00

26 lines
513 B
Markdown

---
title: Value to safe integer
type: snippet
language: javascript
tags: [math]
cover: pagodas
dateModified: 2020-10-22T20:24:44+03:00
---
Converts a value to a safe integer.
- Use `Math.max()` and `Math.min()` to find the closest safe value.
- Use `Math.round()` to convert to an integer.
```js
const toSafeInteger = num =>
Math.round(
Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)
);
```
```js
toSafeInteger('3.2'); // 3
toSafeInteger(Infinity); // 9007199254740991
```