Paraknight Paraknight - 1 year ago 63
Java Question

How do you round a decimal when using the if statement in Java?

I am new to Java and I am coding a credit card Java assignment where you add charges to a credit card and add the interest with the charge. I coded an interest using the If statement but it outputs to a decimal that is not rounded.

public class Credit_Card
public static void main (String []args)
Scanner c = new Scanner (;
double num1, num2, interest, newBalance, min = 0;

int num3 = 50;

System.out.println ("What is the previous balance?");
num1 = c.nextInt();

System.out.println ("What is the total amount of additional charges?");
num2 = c.nextInt();

interest = num2;

if (num2 == 0)
interest = (interest + 0); //There is no interest if num2 is 0

if (num2 > 0)
interest = (interest*(2.0f/100.0f)); //total amount of money owed is multiplied by 2 percent

newBalance = num1 + num2 + interest;

System.out.println ("CS CARD International Statement");
System.out.println ("===============================");
System.out.println ("");
System.out.println ("Previous Balance: $" + num1 );
System.out.println ("Additional Charges: $" + num2 );
System.out.println ("Interest: $" + interest );
System.out.println ("");
System.out.println ("New Balance: $" + newBalance);
System.out.println ("");

if (newBalance < 50)
min = newBalance;

if(newBalance >= 50 && newBalance <= 300)
min = num3;

if(newBalance > 301)
min = (newBalance*(20.0f/100.0f));

System.out.println ("Minimum Payment: $" + min);

The output look like this:

What is the previous balance?
What is the total amount of additional charges?
CS CARD International Statement

Previous Balance: $1000.0
Additional Charges: $25.0
Interest: $0.4999999888241291

New Balance: $1025.4999999888241

Minimum Payment: $205.100003053993

I think that because the interest is an everlasting decimal, it screws up everything else. Instead of the Interest being "0.49999999999", I want it to like like "0.50". Thank you very much in advance for any help.

Kai Kai
Answer Source

String.format ("%.2f", var); where var is your newBalance, etc.

This rounds it to 2 decimal place.

Check out for a list of what you can do with formatter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download