liamzebedee
liamzebedee

Reputation: 14490

How can I round down to the nearest integer from an int array?

I'm designing a donation plugin in Java, from which a user can donate a custom amount. From donating, there are benefits you receive from certain packages.

What I wish to do, is round down an integer n, to the nearest donation package.

For example, there might be 3 donation packages, all represented as integers. There are the $5, the $10, and the $20 donation packages. If a user donates $13, I want the plugin to round that down to $10, as that is the nearest donation package.

Upvotes: 0

Views: 1108

Answers (5)

Nishant
Nishant

Reputation: 55866

Well, I have some free time today. (: Care for the donation array is increasing order.. else just sort it first

public class Donation {
    private static int[] donArray = {10, 5, 30, 20};
    static{
        Arrays.sort(donArray);
    }

    public static void main(String[] args){
        int paid = 13;
        System.out.println("Applied Donation: " + applyDonation(paid));
    }

    private static int applyDonation(int paid) {
        int applied = 0;
        for(int range: donArray){
            if(range <= paid)
                applied = range;
            else
                break;
        }
        return applied;
    }
}

or even simpler this:

    TreeSet<Integer> donSet = new TreeSet<Integer>(Arrays.asList(new Integer[]{10, 5, 30, 20}));
    int paid = 13;
    System.out.println("Applied Donation: " + donSet.floor(paid));

Upvotes: 5

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79867

Put all the values in a TreeSet<Integer>, then use

myTreeSet.headSet( donatedValue ).last();

Upvotes: 1

Shadow
Shadow

Reputation: 6277

You can use binary search on donations array and find the indexes between which your new donation value lies and then decide from the two values easily using if-else.
Edit: you need to have array sorted before hand for it.

Upvotes: 0

Efthymis
Efthymis

Reputation: 1326

Try dividing it by 10, rounding it to the nearest integer and then multiply it again by 10.

eg.

13/10=1.3 -> 1.3~1 -> 1*10 = 10$

or

16/10=1.6 -> 1.6~2 -> 2*10=20$

Of course this will only work in donation packages of 10s.

Upvotes: 0

COD3BOY
COD3BOY

Reputation: 12112

I'm not sure why not this?

if(donation >10 && <=15) {           //say you want to round 15 or less to 10
  donation=10;
 }

Upvotes: 0

Related Questions