【问题标题】:Rounding up a number to nearest multiple of 5将数字四舍五入到最接近 5 的倍数
【发布时间】:2012-03-07 09:33:08
【问题描述】:

有谁知道如何将一个数字四舍五入到最接近的 5 的倍数?我找到了一种算法,可以将它四舍五入到最接近 10 的倍数,但我找不到这个。

这样做十个。

double number = Math.round((len + 5)/ 10.0) * 10.0;

【问题讨论】:

  • 10 的代码是什么样的?将 10 更改为 5 应该相当简单。
  • len 的类型是什么?这是int 还是double
  • 它是双倍的。如果我没有将它初始化为双精度,我认为它会给我一个错误
  • double number = Math.round((len + 2.5)/ 5.0) * 5.0; ??
  • @bestsss 这个问题没有说要舍入整数,是吗?

标签: java rounding


【解决方案1】:
int round(int num) {
    int temp = num%5;
    if (temp<3)
         return num-temp;
    else
         return num+5-temp;
}

【讨论】:

    【解决方案2】:
    int roundUp(int num) {
        return ((num / 5) + (num % 5 > 0 ? 1 : 0)) * 5;
    }
    

    【讨论】:

      【解决方案3】:
      int roundUp(int n) {
          return (n + 4) / 5 * 5;
      }
      

      注意 - YankeeWhiskey 的答案是四舍五入到最接近的倍数,这是四舍五入。如果您需要它来处理负数,则需要进行修改。请注意,整数除法后跟同一个数的整数乘法是向下取整的方法。

      【讨论】:

      • 我们为什么要在数字上加 4?
      【解决方案4】:

      我想我知道了,感谢 Amir

      double round( double num, int multipleOf) {
        return Math.floor((num + multipleOf/2) / multipleOf) * multipleOf;
      }
      

      这是我运行的代码

      class Round {
          public static void main(String[] args){
              System.out.println("3.5 round to 5: " + Round.round(3.5, 5));
              System.out.println("12 round to 6: " + Round.round(12, 6));
              System.out.println("11 round to 7: "+ Round.round(11, 7));
              System.out.println("5 round to 2: " + Round.round(5, 2));
              System.out.println("6.2 round to 2: " + Round.round(6.2, 2));
          }
      
          public static double round(double num, int multipleOf) {
              return Math.floor((num +  (double)multipleOf / 2) / multipleOf) * multipleOf;
          }
      }
      

      这是输出

      3.5 round to 5: 5.0
      12 round to 6: 12.0
      11 round to 7: 14.0
      5 round to 2: 6.0
      6.2 round to 2: 6.0
      

      【讨论】:

      • multipleOf 是一个 int,因此将其除以 2 会导致问题。
      • 如果 multipleOf == 5 那么 multipleOf/2 == 2
      • @AmirPashazadeh:没错,我还需要使用地板,而不是圆形,因为我已经添加了multipleOf/2。看到其他问题了吗?
      【解决方案5】:
      int roundUp(int num) {
          return (int) (Math.ceil(num / 5d) * 5);
      }
      

      【讨论】:

      • 用我的例子对此进行了测试,它可以工作。即使对于任何类型的倍数public static int roundUp(double num, int multipleOf) { return (int) (Math.ceil(num / (double)multipleOf) * multipleOf); }
      【解决方案6】:

      递归:

      public static int round(int n){
          return (n%5==0) ? n : round(++n);
      }
      

      【讨论】:

      • 公式是 (x+y-1)/y,不知道递归是否只是为了看起来很酷,想象一下它是几千 - bam StackOverflow。
      • 你抓住了我。我经常漂浮在堆栈溢出周围,试图看起来很酷。这是一个替代建议。有很多方法。
      • @TimmyO'Mahony 递归在这方面是不必要的并且完全没有效率
      【解决方案7】:

      四舍五入到最接近的任何值

      int round(double i, int v){
          return Math.round(i/v) * v;
      }
      

      您还可以将Math.round() 替换为Math.floor()Math.ceil(),使其始终向下舍入或向上舍入。

      【讨论】:

      • 这是迄今为止最好的答案。它是通用的,它适用于四舍五入到最接近的任何整数(例如 2 或 5)或任何分数(例如 0.1 或 0.05)。
      • 但必须对其进行编辑以获取和返回双精度数才能用于小数
      • 我不知道为什么它实际上没有编译时有这么多投票
      • @SamJakob 当我用 Java 1.8.0_152 编译它时,我得到error: incompatible types: possible lossy conversion from long to int。为了让它编译,您需要转换Math.round 的结果或将返回类型更改为long
      • 提供正确答案的道具。使用不可读变量名的零道具(双 i ,双 v)。
      【解决方案8】:
      if (n % 5 == 1){
         n -= 1;
      } else if (n % 5 == 2) {
         n -= 2;
      } else if (n % 5 == 3) {
         n += 2;
      } else if (n % 5 == 4) {
         n += 1;
      }
      

      【讨论】:

      • YandereDev,是你吗?
      【解决方案9】:

      代码:

      公共课 MyMath { 公共静态无效主要(字符串[]参数){ 运行测试(); } 公共静态双myFloor(双数,双multipleOf){ 返回 ( Math.floor(num / multipleOf) * multipleOf ); } 公共静态双myCeil(双数,双multipleOf){ return ( Math.ceil (num / multipleOf) * multipleOf ); } 私人静态无效运行测试(){ System.out.println("myFloor (57.3, 0.1) : " + myFloor(57.3, 0.1)); System.out.println("myCeil (57.3, 0.1) : " + myCeil (57.3, 0.1)); System.out.println(""); System.out.println("myFloor (57.3, 1.0) : " + myFloor(57.3, 1.0)); System.out.println("myCeil (57.3, 1.0) : " + myCeil (57.3, 1.0)); System.out.println(""); System.out.println("myFloor (57.3, 5.0) : " + myFloor(57.3, 5.0)); System.out.println("myCeil (57.3, 5.0) : " + myCeil (57.3, 5.0)); System.out.println(""); System.out.println("myFloor (57.3, 10.0) : " + myFloor(57.3,10.0)); System.out.println("myCeil (57.3, 10.0) : " + myCeil (57.3,10.0)); } }

      输出:myCeil 中也存在 0.1 倍数的错误……不知道为什么。

      我的地板(57.3,0.1):57.2 myCeil (57.3, 0.1) : 57.300000000000004 我的地板(57.3,1.0):57.0 myCeil (57.3, 1.0) : 58.0 我的地板(57.3,5.0):55.0 myCeil (57.3, 5.0) : 60.0 我的地板(57.3,10.0):50.0 myCeil (57.3, 10.0) : 60.0

      【讨论】:

        【解决方案10】:

        只需将您的数字作为双精度数传递给此函数,它将返回您将十进制值向上舍入到最接近的值 5;

        如果是 4.25,则输出 4.25

        如果是 4.20,则输出 4.20

        如果是 4.24,则输出 4.20

        如果是 4.26,则输出 4.30

        如果要四舍五入到小数点后 2 位,请使用

        DecimalFormat df = new DecimalFormat("#.##");
        roundToMultipleOfFive(Double.valueOf(df.format(number)));
        

        如果最多 3 个位置,则 new DecimalFormat("#.###")

        如果最多 n 个位置,则 new DecimalFormat("#.nTimes #")

         public double roundToMultipleOfFive(double x)
                    {
        
                        x=input.nextDouble();
                        String str=String.valueOf(x);
                        int pos=0;
                        for(int i=0;i<str.length();i++)
                        {
                            if(str.charAt(i)=='.')
                            {
                                pos=i;
                                break;
                            }
                        }
        
                        int after=Integer.parseInt(str.substring(pos+1,str.length()));
                        int Q=after/5;
                        int R =after%5;
        
                        if((Q%2)==0)
                        {
                            after=after-R;
                        }
                        else
                        {
                            after=after+(5-R);
                        }
        
                               return Double.parseDouble(str.substring(0,pos+1).concat(String.valueOf(after))));
        
                    }
        

        【讨论】:

          【解决方案11】:

          这是我用来四舍五入为数字的倍数的方法:

          private int roundToMultipleOf(int current, int multipleOf, Direction direction){
              if (current % multipleOf == 0){
                  return ((current / multipleOf) + (direction == Direction.UP ? 1 : -1)) * multipleOf;
              }
              return (direction == Direction.UP ? (int) Math.ceil((double) current / multipleOf) : (direction == Direction.DOWN ? (int) Math.floor((double) current / multipleOf) : current)) * multipleOf;
          }
          

          变量current 是您要四舍五入的数字,multipleOf 是您想要的倍数(即四舍五入到最接近的 20、最接近的 10 等),direction 是我创建的枚举向上或向下舍入。

          祝你好运!

          【讨论】:

            【解决方案12】:

            有人说

            int n = [some number]
            int rounded = (n + 5) / 5 * 5;
            

            这将四舍五入,例如,5 到 10,以及 6、7、8 和 9(全部到 10)。你不希望 5 舍入到 10。仅处理整数时,您希望将 4 添加到 n 而不是 5。因此,使用该代码并将 5 替换为 4:

            int n = [some number]
            int rounded = (n + 4) / 5 * 5;
            

            当然,在处理双打时,只需输入类似 4.99999 的内容,或者如果您想考虑所有情况(如果您可能正在处理更精确的双打),请添加条件语句:

            int n = [some number]
            int rounded = n % 5 == 0 ? n : (n + 4) / 5 * 5;
            

            【讨论】:

              【解决方案13】:

              将数字四舍五入到最接近 5 的倍数的另一种方法或逻辑

              double num = 18.0;
                  if (num % 5 == 0)
                      System.out.println("No need to roundoff");
                  else if (num % 5 < 2.5)
                      num = num - num % 5;
                  else
                      num = num + (5 - num % 5);
                  System.out.println("Rounding up to nearest 5------" + num);
              

              输出:

              Rounding up to nearest 5------20.0
              

              【讨论】:

                【解决方案14】:

                将给定数字四舍五入到最接近的 5 的倍数。

                public static int round(int n)
                  while (n % 5 != 0) n++;
                  return n; 
                }
                

                【讨论】:

                • 这是最糟糕的方法之一,因为它需要多次进行慢速除法
                【解决方案15】:

                我创建了一种方法,可以将数字转换为将传入的最接近的数字,也许它会对某人有所帮助,因为我在这里看到了很多方法,但它对我没有用,但这个方法可以:

                /**
                 * The method is rounding a number per the number and the nearest that will be passed in.
                 * If the nearest is 5 - (63->65) | 10 - (124->120).
                 * @param num - The number to round
                 * @param nearest - The nearest number to round to (If the nearest is 5 -> (0 - 2.49 will round down) || (2.5-4.99 will round up))
                 * @return Double - The rounded number
                 */
                private Double round (double num, int nearest) {
                    if (num % nearest >= nearest / 2) {
                        num = num + ((num % nearest - nearest) * -1);
                    } else if (num % nearest < nearest / 2) {
                        num = num - (num % nearest);
                    }
                    return num;
                }
                

                【讨论】:

                • 不适用于 31.428 => 31 ,但在最近 =1 时有效 32
                【解决方案16】:

                如果您只需要对整数进行四舍五入,您可以使用此功能:

                public static long roundTo(long value, long roundTo) {
                    if (roundTo <= 0) {
                        throw new IllegalArgumentException("Parameter 'roundTo' must be larger than 0");
                    }
                    long remainder = value % roundTo;
                    if (Math.abs(remainder) < (roundTo / 2d)) {
                        return value - remainder;
                    } else {
                        if (value > 0) {
                            return value + (roundTo - Math.abs(remainder));
                        } else {
                            return value - (roundTo - Math.abs(remainder));
                        }
                    }
                }
                

                优点是它使用整数运算,甚至适用于浮点除法会导致问题的大长数。

                【讨论】:

                  【解决方案17】:
                  int roundUp(int n, int multipleOf)
                  {
                    int a = (n / multipleOf) * multipleOf;
                    int b = a + multipleOf;
                    return (n - a > b - n)? b : a;
                  }
                  

                  来源:https://www.geeksforgeeks.org/round-the-given-number-to-nearest-multiple-of-10/

                  【讨论】:

                    【解决方案18】:
                    int getNextMultiple(int num , int multipleOf) {
                        int nextDiff = multipleOf - (num % multipleOf);
                        int total = num + nextDiff;
                        return total;
                    }
                    

                    【讨论】:

                      【解决方案19】:
                       int roundToNearestMultiple(int num, int multipleOf){
                              int floorNearest = ((int) Math.floor(num * 1.0/multipleOf)) * multipleOf;
                              int ceilNearest = ((int) Math.ceil(num  * 1.0/multipleOf)) * multipleOf;
                              int floorNearestDiff = Math.abs(floorNearest - num);
                              int ceilNearestDiff = Math.abs(ceilNearest - num);
                              if(floorNearestDiff <= ceilNearestDiff) {
                                  return floorNearest;
                              } else {
                                  return ceilNearest;
                              } 
                          }
                      

                      【讨论】:

                        【解决方案20】:

                        这个 Kotlin 函数将给定值 'x' 舍入到最接近的 'n' 倍数

                        fun roundXN(x: Long, n: Long): Long {
                            require(n > 0) { "n(${n}) is not greater than 0."}
                        
                            return if (x >= 0)
                                ((x + (n / 2.0)) / n).toLong() * n
                            else
                                ((x - (n / 2.0)) / n).toLong() * n
                        }
                        
                        fun main() {
                            println(roundXN(121,4))
                        }
                        

                        输出:120

                        【讨论】:

                          【解决方案21】:

                          你可以使用这个方法Math.round(38/5) * 5得到5的倍数

                          它可以替换为Math.ceilMath.floor,具体取决于您要如何四舍五入

                          【讨论】:

                            【解决方案22】:

                            带有扩展功能的 Kotlin。

                            可能在play.kotlinlang.org上运行

                            import kotlin.math.roundToLong
                            
                            fun Float.roundTo(roundToNearest: Float): Float = (this / roundToNearest).roundToLong() * roundToNearest
                            
                            fun main() {    
                                println(1.02F.roundTo(1F)) // 1.0
                                println(1.9F.roundTo(1F)) // 2.0
                                println(1.5F.roundTo(1F)) // 2.0
                            
                                println(1.02F.roundTo(0.5F)) // 1.0
                                println(1.19F.roundTo(0.5F)) // 1.0
                                println(1.6F.roundTo(0.5F)) // 1.5
                                
                                println(1.02F.roundTo(0.1F)) // 1.0
                                println(1.19F.roundTo(0.1F)) // 1.2
                                println(1.51F.roundTo(0.1F)) // 1.5
                            }
                            

                            可以像这样使用地板/天花板: fun Float.floorTo(roundToNearest: Float): Float = floor(this / roundToNearest) * roundToNearest

                            【讨论】:

                              【解决方案23】:

                              Praveen Kumars 在此线程的其他地方提出问题

                              “为什么我们要在数字上加 4?”

                              非常相关。这就是为什么我更喜欢这样编码:

                              int roundUpToMultipleOf5(final int n) {
                                  return (n + 5 - 1) / 5 * 5;
                              }
                              

                              或者,将值作为参数传递:

                              int roundUpToMultiple(final int n, final int multipleOf) {
                                  return (n + multipleOf - 1) / multipleOf * multipleOf;
                              }
                              

                              通过比您要查找的倍数少 1,您已添加 刚好 以确保 n 的值是一个精确的倍数 不会 向上取整,任何n 的值不是精确的倍数向上取整到下一个倍数。

                              【讨论】:

                                猜你喜欢
                                • 2011-03-25
                                • 2011-03-16
                                • 1970-01-01
                                • 1970-01-01
                                • 2021-04-08
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                相关资源
                                最近更新 更多