Search code examples
javamathnumber-formattingpercentage

how to use percentages in java


public class BankAccount{
    public int number;
    private double balance;
    public boolean transfer(double amount){
    /*transfer money between BankAccount taking into consideration that a maximum of 50% of the BankAccount      balance can be transferred.*/
    if(amount > 0 && balance >= 50.0){
    balance = balance - amount;
    }
    return true;
    }
    return false;
    }

I don't know how to use percentages in java.
so how can i handle the 50% of the balance in percentage?


Solution

  • 50% of a number is its half, so you can use balance / 2 to get 50% of a balance, also consider the initial value of a balance -> if you don't initialize it it will be 0.0 by default (primitive type default value) thus you will always get false for transfer answer. You can try something like this:

    class BankAccount{
        private double balance = 2000.0;
        
        public boolean transfer(double amount){
            //transfer money between BankAccount taking into consideration
            //that a maximum of 50% of the BankAccount balance can be transferred.
            if(amount > 0 && amount <= balance / 2.0){
                balance = balance - amount;
                return true;
            }
            return false;
        }
    }
    

    In general if you want to get some percent of a number you can multiple number with percentage/100.0 For example:

    double balance = 1000.0;
    double _36_percents_of_balance = balance * 36/100.0;