w3resource

JavaScript: Convert a value to a safe integer

JavaScript fundamental (ES6 Syntax): Exercise-121 with Solution

Write a JavaScript program to convert 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.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2

// Define the 'toSafeInteger' function.
const toSafeInteger = num =>
  Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));

// Test the 'toSafeInteger' function with sample inputs.
console.log(toSafeInteger('3.2')); // Output: 3
console.log(toSafeInteger(Infinity)); // Output: 9007199254740991 (maximum safe integer)

Output:

3
9007199254740991

Visual Presentation:

JavaScript Fundamental: Convert a value to a safe integer.

Flowchart:

flowchart: Convert a value to a safe integer

Live Demo:

See the Pen javascript-basic-exercise-121-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to convert a string to snake case.
Next: Write a JavaScript program to add an ordinal suffix to a number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.