1

So I am making a fitness app for android and now I am asking the user to input a number e.g. 72.5

I would take this number and take percentages of it and apply functions to this etc.

I need to make sure that the percentage I take of that number is rounded to 2.5. This is because in a UK gym you only have the following plates: 1.25x2=2.5 2.5x2=5 5+2.5=7.5 , 10, 15, 20, 25

What I mean is that it would be numbers like these: 40, 42.5, 45, 47.5, 50

How can I round a Number N to the nearest 2.5? I understand that math.Round() rounds to nearest whole but what about to a custom number like this?

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
  • Sorry if there is any unncessary info there but I thought it would be helpful to provide context –  Mar 16 '20 at 19:35
  • 1
    https://stackoverflow.com/questions/23449662/java-round-to-nearest-5 maybe thisone help – Edgar Mar 16 '20 at 19:38

2 Answers2

1

Do it as follows:

public class Main {
    public static void main(String args[]) {
        // Tests
        System.out.println(roundToNearest2Point5(12));
        System.out.println(roundToNearest2Point5(14));
        System.out.println(roundToNearest2Point5(13));
        System.out.println(roundToNearest2Point5(11));
    }

    static double roundToNearest2Point5(double n) {
        return Math.round(n * 0.4) / 0.4;
    }
}

Output:

12.5
15.0
12.5
10.0

Explanation:

It will be easier to understand with the following example:

double n = 20 / 3.0;
System.out.println(n);
System.out.println(Math.round(n));
System.out.println(Math.round(n * 100.0));
System.out.println(Math.round(n * 100.0) / 100.0);

Output:

6.666666666666667
7
667
6.67

As you can see here, rounding 20 / 3.0 returns 7 (which is the floor value after adding 0.5 to 20 / 3.0. Check this to understand the implementation). However, if you wanted to round it up to the nearest 1/100th place (i.e. up to 2 decimal places), an easier way (but not so precise. Check this for more precise way) would be to round n * 100.0 (which would make it 667) and then divide it by 100.0 which would give 6.67 (i.e. up to 2 decimal places). Note that 1 / (1 / 100.0) = 100.0

Similarly, to round the number to the nearest 2.5th place, you will need to do the same thing with 1 / 2.5 = 0.4 i.e. Math.round(n * 0.4) / 0.4.

To round a number to the nearest 100th place, you will need to do the same thing with 1 / 100 = 0.01 i.e. Math.round(n * 0.1) / 0.1.

To round a number to the nearest 0.5th place, you will need to do the same thing with 1 / 0.5 = 2.0 i.e. Math.round(n * 2.0) / 2.0.

I hope, it is clear.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

Late reply but you can also do 2.5*(Math.round(number/2.5)) Same way if you wanted to round in lbs to the nearest 5th its 5*(Math.round(number/5))

Mauricio
  • 11
  • 1
  • 2