Round a float to the nearest multiple of ?

后端 未结 2 1625
忘掉有多难
忘掉有多难 2021-01-29 15:57

How do I round a float value to the nearest multiple of \"n\"?

For instance, rounding 21.673 to the nearest multiple of 8 should result in 24.

And, rounding 21.6

相关标签:
2条回答
  • 2021-01-29 16:08

    It is easy

    Math.round(value / n) * n
    
    0 讨论(0)
  • 2021-01-29 16:10

    There's another one, slightly shorter, slightly faster:

    const nearrestMultipleOfN = (N,n) => n*(N/n+0.5|0);
    

    It seems to deliver what's expected:

    const nearrestMultipleOfN = (N,n) => n*(N/n+0.5|0);
     
     console.log(nearrestMultipleOfN(21.673,8));
     console.log(nearrestMultipleOfN(21.673,4));
    .as-console-wrapper{min-height:100%}

    If you find yourself looking for the greatest integer divisible by n that does not exceed N (i.e. return 6, divisible by 3, when given 8), you might go, like:

    const nearrestMultipleOfN = (N,n) => n*(N/n|0);
    
    0 讨论(0)
提交回复
热议问题