# Thread: Need help with truncating decimals?

1. Member
Join Date
Oct 2011
Posts
31
Rep Power
0

## Need help with truncating decimals?

I can't shave off the decimals for final balance. Since the other values are in double, i cant change finalBalance to an int or other forms. Also when i enter too many numbers eg. 1000000, the program is stuck in the while part.

here is my code:
Java Code:
```import java.util.Scanner;
public class Args{

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

double iBalance;
int month=0;
int year=0;
int finalBalance;

iBalance=in.nextInt();
in.close();
System.out.println("Balance is:\n"+iBalance);
while (iBalance > 500)
{
iBalance = iBalance*(1.005)-500;
month++;
}

while (month>=12)
{
year = month/12;
month = month-12;
}
if (year > 0)
{
System.out.println (+year+" years and " +month+" months");
}
else
{
System.out.println (+month+" months");
}

finalBalance = iBalance;
System.out.println ("Remaning Balance:\n" +finalBalance);
}
}```

2. Member
Join Date
Oct 2011
Posts
31
Rep Power
0

## Re: Need help with truncating decimals?

bump!!!! :)

3. Senior Member
Join Date
Nov 2010
Posts
210
Rep Power
4

## Re: Need help with truncating decimals?

Use System.out.printf() or DecimalFormat.

I'm pretty sure this doesn't do what you intend it to:
Java Code:
```       while (month>=12)
{
year = month/12;
month = month-12;
}```
Looks like you're trying to increase year by month/12, but it will always end up being 0 or 1 because the loop keeps decreasing month by 12.

Oh, and the reason for the infinite loop is that if iBalance is high enough, multiplying it by 1.005 and subtracting 500 will cause it to constantly go up, so the loop condition will always be true.
Last edited by Iron Lion; 10-05-2011 at 01:07 AM.

4. Member
Join Date
Oct 2011
Posts
31
Rep Power
0

## Re: Need help with truncating decimals?

how can i stop the loop condition to continously go up? thanks for the help.

also i tried using System.out.printf

but it is telling me :

Exception in thread "main" java.util.IllegalFormatPrecisionException: 2
at java.util.Formatter\$FormatSpecifier.checkText(Unkn own Source)
at java.util.Formatter\$FormatSpecifier.<init>(Unknown Source)
at java.util.Formatter.parse(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at Args.main(Args.java:37)

i have used:

import java.util.Formatter, but it still gives me the message.

Edit* never mind i found out what i did wrong.

I wrote System.out.printf ("remaning balance: %10.2f%" +iBalance); which doesnt work

System.out.printf("Remaning Balance:%10.2f",iBalance); works.

edit*
The code to increment years work because if month is 0 or less than 12 it moves on.
Last edited by akeni; 10-05-2011 at 02:05 AM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•