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

时间:2012-02-16 00:06:03

标签: java rounding

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

这是十年。

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

23 个答案:

答案 0 :(得分:92)

舍入到最接近的任何值

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

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

答案 1 :(得分:50)

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

注意 - YankeeWhiskey的答案是四舍五入到最接近的倍数,这是四舍五入。如果您需要修改负数,则需要修改。请注意,整数除法后跟相同数字的整数乘法是向下舍入的方式。

答案 2 :(得分:11)

我想我拥有它,感谢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

答案 3 :(得分:9)

int roundUp(int num) {
    return (int) (Math.ceil(num / 5d) * 5);
}

答案 4 :(得分:5)

int roundUp(int num) {
    return ((num / 5) + (num % 5 > 0 ? 1 : 0)) * 5;
}

答案 5 :(得分:5)

int round(int num) {
    int temp = num%5;
    if (temp<3)
         return num-temp;
    else
         return num+5-temp;
}

答案 6 :(得分:2)

此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

答案 7 :(得分:1)

有些人说的是

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

这将围绕,例如,5到10,以及6,7,8和9(全部到10)。你不希望5轮到10。在处理只是整数时,你想要改为将4添加到n而不是5.因此,取代码并用4替换5:

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;

答案 8 :(得分:1)

int getNextMultiple(int num , int multipleOf) {
    int nextDiff = multipleOf - (num % multipleOf);
    int total = num + nextDiff;
    return total;
}

答案 9 :(得分:1)

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

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

答案 10 :(得分:1)

将数字四舍五入为最接近的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

答案 11 :(得分:0)

这是我用于舍入到数字的倍数的内容:

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等),{{1}我是一个枚举,无论是向上还是向下。

祝你好运!

答案 12 :(得分:0)

只需将您的号码作为双精度传递给此函数,它会返回四舍五入到最接近的值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个地方,新的DecimalFormat(&#34;#。###&#34;)

如果最多n个地方,新的DecimalFormat(&#34;#。 nTimes#&#34;)

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

            }

答案 13 :(得分:0)

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

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

答案 14 :(得分:0)

如果您只需要围绕整数,您可以使用此功能:

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

优点是它使用整数算术,甚至可以用于大数字长数,浮点除法会导致问题。

答案 15 :(得分:0)

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/

答案 16 :(得分:0)

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

答案 17 :(得分:0)

递归:

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

答案 18 :(得分:0)

您可以使用此方法fs2.writeFileSync('./randomstuff.txt', splitData.join('\n')); 获得5的倍数

根据您希望取整数字的方式,可以将其替换为Math.round(38/5) * 5Math.ceil

答案 19 :(得分:0)

带有扩展功能的 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

答案 20 :(得分:0)

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不是一个精确的倍数四舍五入到下一个倍数。

答案 21 :(得分:-1)

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

答案 22 :(得分:-4)

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

输出: 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
相关问题