JavaScript: Convert a value to a safe integer
JavaScript fundamental (ES6 Syntax): Exercise-29 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 a function named to_Safe_Integer that converts a given number to a safe integer.
const to_Safe_Integer = num =>
Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));
// Test the function with different input values.
console.log(to_Safe_Integer('5.2')); // Output: 5
console.log(to_Safe_Integer('5.52')); // Output: 6
console.log(to_Safe_Integer(Infinity)); // Output: 9007199254740991 (MAX_SAFE_INTEGER)
Output:
5 6 9007199254740991
Flowchart:
Live Demo:
See the Pen javascript-basic-exercise-1-29 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to measure the time taken by a function to execute.
Next: Write a JavaScript program to filter out the element(s) of an given array, that have one of the specified values.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-29.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics