How to round integer in java

后端 未结 12 775
野趣味
野趣味 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:27

    I usually do it this way:

    int num = 1732;
    int roundedNum = Math.round((num + 9)/10 * 10);
    

    This will give you 1740 as the result.

    Hope this will help.

    0 讨论(0)
  • 2020-12-09 09:29

    very simple. try this

    int y = 173256457;int x = (y/10)*10; 
    

    Now in this you can replace 10 by 100,1000 and so on....

    0 讨论(0)
  • 2020-12-09 09:36

    Have you looked at the implementation of Mathutils.round() ? It's all based on BigDecimal and string conversions. Hard to imagine many approaches that are less efficient.

    0 讨论(0)
  • 2020-12-09 09:37

    At nearest ten:

    int i = 1986;
    int result;
    
    result = i%10 > 5 ? ((i/10)*10)+10 : (i/10)*10;
    

    (Add zero's at will for hundred and thousand).

    0 讨论(0)
  • 2020-12-09 09:39
    (int)(Math.round( 1732 / 10.0) * 10)
    

    Math.round(double) takes the double and then rounds up as an nearest integer. So, 1732 will become 173.2 (input parameter) on processing by Math.round(1732 / 10.0). So the method rounds it like 173.0. Then multiplying it with 10 (Math.round( 1732 / 10.0) * 10) gives the rounded down answer, which is 173.0 will then be casted to int.

    0 讨论(0)
  • 2020-12-09 09:40

    You could try:

    int y = 1732;
    int x = y - y % 10;
    

    The result will be 1730.

    Edit: This doesn't answer the question. It simply removes part of the number but doesn't "round to the nearest".

    0 讨论(0)
提交回复
热议问题