How to round integer in java

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

    Its very easy..

    int x = 1234; int y = x - x % 10; //It will give 1230

    int y = x - x % 100; //It will give 1200

    int y = x - x % 1000; //It will give 1000

    The above logic will just convert the last digits to 0. If you want actual round of// For eg. 1278 this should round off to 1280 because last digit 8 > 5 for this i wrote a function check it out.

     private double returnAfterRoundDigitNum(double paramNumber, int noOfDigit)  
        {  
         double tempSubtractNum = paramNumber%(10*noOfDigit);  
         double tempResultNum = (paramNumber - tempSubtractNum);  
         if(tempSubtractNum >= (5*noOfDigit))  
          {  
              tempResultNum = tempResultNum + (10*noOfDigit);  
          }  
          return tempResultNum;  
       }  
    

    Here pass 2 parameters one is the number and the other is position till which you have to round off.

    Regards, Abhinav

提交回复
热议问题