How to round an integer up or down to the nearest 10 using Javascript

后端 未结 4 1856
你的背包
你的背包 2020-11-27 19:04

Using Javascript, I would like to round a number passed by a user to the nearest 10. For example, if 7 is passed I should return 10, if 33 is passed I should return 30.

相关标签:
4条回答
  • 2020-11-27 19:06
    Math.round(x / 10) * 10
    
    0 讨论(0)
  • 2020-11-27 19:13

    Divide the number by 10, round the result and multiply it with 10 again:

    var number = 33;
    console.log(Math.round(number / 10) * 10);

    0 讨论(0)
  • 2020-11-27 19:18

    Where i is an int.

    To round down to the nearest multiple of 10 i.e.

    11 becomes 10
    19 becomes 10
    21 becomes 20

    parseInt(i / 10, 10) * 10;
    

    To round up to the nearest multiple of 10 i.e.

    11 becomes 20
    19 becomes 20
    21 becomes 30

    parseInt(i / 10, 10) + 1 * 10;  
    
    0 讨论(0)
  • 2020-11-27 19:20

    I needed something similar, so I wrote a function. I used the function for decimal rounding here, and since I also use it for integer rounding, I will set it as the answer here too. In this case, just pass in the number you want to round and then 10, the number you want to round to.

    function roundToNearest(numToRound, numToRoundTo) {
        return Math.round(numToRound / numToRoundTo) * numToRoundTo;
    }
    
    0 讨论(0)
提交回复
热议问题