Rounding up a number to nearest multiple of 5

后端 未结 21 2020
感动是毒
感动是毒 2020-11-27 15:24

Does anyone know how to round up a number to its nearest multiple of 5? I found an algorithm to round it to the nearest multiple of 10 but I can\'t find this one.

T

21条回答
  •  心在旅途
    2020-11-27 16:21

    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;

    if 4.25, Output 4.25

    if 4.20, Output 4.20

    if 4.24, Output 4.20

    if 4.26, Output 4.30

    if you want to round upto 2 decimal places,then use

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

    if up to 3 places, new DecimalFormat("#.###")

    if up to n places, new DecimalFormat("#.nTimes #")

     public double roundToMultipleOfFive(double x)
                {
    
                    x=input.nextDouble();
                    String str=String.valueOf(x);
                    int pos=0;
                    for(int i=0;i

提交回复
热议问题