How to round integer in java

后端 未结 12 862
野趣味
野趣味 2020-12-09 09:19

I want to round the number 1732 to the nearest ten, hundred and thousand. I tried with Math round functions, but it was written only for float and double. How to do this for

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 09:52

    What rounding mechanism do you want to use? Here's a primitive approach, for positive numbers:

    int roundedNumber = (number + 500) / 1000 * 1000;
    

    This will bring something like 1499 to 1000 and 1500 to 2000.

    If you could have negative numbers:

    int offset = (number >= 0) ? 500 : -500;
    int roundedNumber = (number + offset) / 1000 * 1000;
    

提交回复
热议问题