Skip to content
Advertisement

Get integer number in interval with JavaScript

I want to know which is the best method to get the integer/whole number in interval with native JavaScript function?

for example if I have [1.3, 2.5] ==> given result: 2

Advertisement

Answer

You could use the integer value from the left value and the ceiled value from the right value and get the integer value from the middled value.

function middleInt(interval) {
    return Math.floor((Math.floor(interval[0]) + Math.ceil(interval[1])) / 2);
}

console.log(middleInt([1.3, 2.5]));
console.log(middleInt([1.3, 1.8]));
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement