This question has already been answered:

How to round, for example, the number 2.35 to 2.5 and the number 3.76 to 4 with the help of JS? You need a dynamic system that could round the number to the nearest half, or to the whole number.

Reported as a duplicate by Igor , Grundy javascript 4 Sep '17 at 6:22 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Pay attention to the version of Andrew, it works with the whole range of numbers and much more concise. My version is more complex and works only with the range N> = 1 - MedvedevDev

3 answers 3

Based on how I understood the task (only for positive numbers greater than or equal to 1):

function numRound(num) { let d = Math.floor(num), i = num%d; return i < .25 ? d : (i < .75 ? d + .5 : d + 1); } console.log(numRound(2)); // 2 console.log(numRound(2.01)); // 2 console.log(numRound(2.24)); // 2 console.log(numRound(2.25)); // 2.5 console.log(numRound(2.5)); // 2.5 console.log(numRound(2.74)); // 2.5 console.log(numRound(2.75)); // 3 console.log(numRound(2.99)); // 3 console.log(numRound(3)); // 3 

    1) Multiply by 2.
    2) Round to the nearest integer.
    3) Divide by 2.

     function numRound(num) { return Math.round(num * 2) / 2; } console.log(numRound(2)); // 2 console.log(numRound(2.01)); // 2 console.log(numRound(2.24)); // 2 console.log(numRound(2.25)); // 2.5 console.log(numRound(2.5)); // 2.5 console.log(numRound(2.74)); // 2.5 console.log(numRound(2.75)); // 3 console.log(numRound(2.99)); // 3 console.log(numRound(-1.01));// -1 console.log(numRound(-1.26));// -1.5 console.log(numRound(-1.74));// -1.5 console.log(numRound(-1.76));// -2 console.log(numRound(-0.26));// -0.5 

    You can make a universal function, in which the transfer accuracy:

     function numRound(num, precision) { return Math.round(num / precision) * precision; } console.log(numRound(2, 0.5)); // 2 console.log(numRound(2.31, 0.5)); // 2.5 console.log(numRound(2.24, 0.2)); // 2.2 console.log(numRound(2.51, 0.2)); // 2.6 console.log(numRound(153, 2)); // 154 console.log(numRound(170, 50)); // 150 console.log(numRound(206, 10)); // 210 

      Use Math.round . If, after applying it, the result is less than the original, then it is necessary to add 0.5 to the result. For numbers from N.5, Math.round will give an integer

      • Math.round(2.17) // 2 - you need 2.5, because 2 <2.17, but it should be 2. - MedvedevDev
      • @MedvedevDev Well, I understand that he needs to round off from N.00001 to N.4999999 to half. otherwise, the border is blurred when it is necessary to round down and when to N.5 - Aleksey Shimansky
      • 2
        As far as I understand, he needs N.01 - N.24 to round to N; N.25 - N.74 round up to N.5; N.75 - N.99 round up to N + 1; I need clarification from the author. - MedvedevDev