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

后端 未结 4 1870
你的背包
你的背包 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: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;  
    

提交回复
热议问题