简体   繁体   English

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

[英]Rounding up a number to nearest multiple of 5

Does anyone know how to round up a number to its nearest multiple of 5?有谁知道如何将一个数字四舍五入到最接近的 5 的倍数? I found an algorithm to round it to the nearest multiple of 10 but I can't find this one.我找到了一种算法,可以将它四舍五入到最接近的 10 倍数,但我找不到这个。

This does it for ten.这样做十个。

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

To round to the nearest of any value四舍五入到最接近的任何值

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

You can also replace Math.round() with either Math.floor() or Math.ceil() to make it always round down or always round up.您还可以将Math.round()替换为Math.floor()Math.ceil()以使其始终向下舍入或始终向上舍入。

int roundUp(int n) {
    return (n + 4) / 5 * 5;
}

Note - YankeeWhiskey's answer is rounding to the closest multiple, this is rounding up.注意 - YankeeWhiskey 的答案是四舍五入到最接近的倍数,这是四舍五入。 Needs a modification if you need it to work for negative numbers.如果您需要它来处理负数,则需要进行修改。 Note that integer division followed by integer multiplication of the same number is the way to round down.请注意,整数除法后跟相同数字的整数乘法是向下舍入的方法。

I think I have it, thanks to Amir我想我知道了,感谢Amir

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

Here's the code I ran这是我运行的代码

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;
    }
}

And here's the output这是输出

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
int roundUp(int num) {
    return (int) (Math.ceil(num / 5d) * 5);
}
int round(int num) {
    int temp = num%5;
    if (temp<3)
         return num-temp;
    else
         return num+5-temp;
}
int roundUp(int num) {
    return ((num / 5) + (num % 5 > 0 ? 1 : 0)) * 5;
}
int getNextMultiple(int num , int multipleOf) {
    int nextDiff = multipleOf - (num % multipleOf);
    int total = num + nextDiff;
    return total;
}
 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;
        } 
    }

This Kotlin function rounds a given value 'x' to the closest multiple of 'n'这个 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))
}

Output: 120输出:120

Kotlin with extension function.带有扩展功能的 Kotlin。

Possible run on play.kotlinlang.org可能在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
}

Possible to use floor/ceil like this: fun Float.floorTo(roundToNearest: Float): Float = floor(this / roundToNearest) * roundToNearest可以像这样使用 floor/ceil: fun Float.floorTo(roundToNearest: Float): Float = floor(this / roundToNearest) * roundToNearest

Some people are saying something like有些人在说类似

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

This will round, say, 5 to 10, as well as 6, 7, 8, and 9 (all to 10).例如,这将舍入 5 到 10,以及 6、7、8 和 9(全部到 10)。 You don't want 5 to round to 10 though.你不希望 5 舍入到 10。 When dealing with just integers, you want to instead add 4 to n instead of 5. So take that code and replace the 5 with a 4:当只处理整数时,您希望将 4 添加到 n 而不是 5。因此,使用该代码并将 5 替换为 4:

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

Of course, when dealing with doubles, just put something like 4.99999, or if you want to account for all cases (if you might be dealing with even more precise doubles), add a condition statement:当然,在处理双打时,只需输入类似 4.99999 的内容,或者如果您想考虑所有情况(如果您可能正在处理更精确的双打),请添加条件语句:

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

Another Method or logic to rounding up a number to nearest multiple of 5将数字四舍五入到最接近 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);

output :输出 :

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

I've created a method that can convert a number to the nearest that will be passed in, maybe it will help to someone, because i saw a lot of ways here and it did not worked for me but this one did:我创建了一种方法,可以将一个数字转换为将要传入的最接近的数字,也许它会对某人有所帮助,因为我在这里看到了很多方法,但它对我没有用,但这个方法可以:

/**
 * 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;
}

In case you only need to round whole numbers you can use this function:如果您只需要对整数进行四舍五入,则可以使用此功能:

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));
        }
    }
}

The advantage is that it uses integer arithmetics and works even for large long numbers where the floating point division will cause you problems.优点是它使用整数算术,甚至适用于浮点除法会导致问题的大长数。

int roundUp(int n, int multipleOf)
{
  int a = (n / multipleOf) * multipleOf;
  int b = a + multipleOf;
  return (n - a > b - n)? b : a;
}

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

Praveen Kumars question elsewhere in this Thread Praveen Kumars 在此线程的其他地方提出问题

"Why are we adding 4 to the number?" “为什么我们要在数字上加 4?”

is very relevant.非常相关。 And it is why I prefer to code it like this:这就是为什么我更喜欢这样编码:

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

or, passing the value as an argument:或者,将值作为参数传递:

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

By adding 1 less than the multiple you're looking for, you've added just enough to make sure that a value of n which is an exact multiple will not round up, and any value of n which is not an exact multiple will be rounded up to the next multiple.通过比您要查找的倍数少加 1,您已经添加了足够多的值以确保n的精确倍数不会四舍五入,并且n的任何不是精确倍数的值都将是四舍五入到下一个倍数。

Just pass your number to this function as a double, it will return you rounding the decimal value up to the nearest value of 5;只需将您的数字作为双精度数传递给此函数,它将返回您将十进制值向上舍入到最接近的值 5;

if 4.25, Output 4.25如果为 4.25,则输出 4.25

if 4.20, Output 4.20如果是 4.20,输出 4.20

if 4.24, Output 4.20如果是 4.24,输出 4.20

if 4.26, Output 4.30如果为 4.26,则输出 4.30

if you want to round upto 2 decimal places,then use如果要四舍五入到小数点后 2 位,请使用

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

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

if up to n places, new DecimalFormat("#. nTimes # ")如果最多 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))));

            }

Here's what I use for rounding to multiples of a number:这是我用于四舍五入为数字的倍数的方法:

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;
}

The variable current is the number you're rounding, multipleOf is whatever you're wanting a multiple of (ie round to nearest 20, nearest 10, etc), and direction is an enum I made to either round up or down.变量current是您要四舍五入的数字, multipleOf是您想要的倍数(即四舍五入到最接近的 20、最接近的 10 等),而direction是我做的向上或向下舍入的枚举。

Good luck!祝你好运!

Round a given number to the nearest multiple of 5.将给定数字四舍五入到最接近的 5 的倍数。

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

You can use this method Math.round(38/5) * 5 to get multiple of 5您可以使用此方法Math.round(38/5) * 5获得 5 的倍数

It can be replace with Math.ceil or Math.floor based on how you want to round off the number它可以根据您希望如何四舍五入的数字替换为Math.ceilMath.floor

Use this method to get nearest multiple of 5.使用此方法获得最接近 5 的倍数。

private int giveNearestMul5(int givenValue){
    int roundedNum = 0;
    int prevMul5, nextMul5;
    prevMul5 = givenValue - givenValue%5;
    nextMul5 = prevMul5 + 5;
    if ((givenValue%5!=0)){
        if ( (givenValue-prevMul5) < (nextMul5-givenValue) ){
            roundedNum = prevMul5;
        } else {
            roundedNum = nextMul5;
        }
    } else{
        roundedNum = givenValue;
    }

    return roundedNum;
}

Recursive:递归:

public static int round(int n){
    return (n%5==0) ? n : round(++n);
}
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;
}

CODE:代码:

public class MyMath
    {
        public static void main(String[] args) {
            runTests();
        }
        public static double myFloor(double num, double multipleOf) {
            return ( Math.floor(num / multipleOf) * multipleOf );
        }
        public static double myCeil (double num, double multipleOf) {
            return ( Math.ceil (num / multipleOf) * multipleOf );
        }

        private static void runTests() {
            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));
        }
    }

OUTPUT: There is a bug in the myCeil for multiples of 0.1 too ... no idea why.输出: myCeil 中也存在 0.1 倍数的错误……不知道为什么。

myFloor (57.3,  0.1) : 57.2
    myCeil  (57.3,  0.1) : 57.300000000000004

    myFloor (57.3,  1.0) : 57.0
    myCeil  (57.3,  1.0) : 58.0

    myFloor (57.3,  5.0) : 55.0
    myCeil  (57.3,  5.0) : 60.0

    myFloor (57.3, 10.0) : 50.0
    myCeil  (57.3, 10.0) : 60.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM