d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Can Someone Help Me Format This?
Add Reply New Topic New Poll
Member
Posts: 6,106
Joined: Jun 22 2008
Gold: 116.80
Mar 3 2013 05:11pm
Sorry I'm very new to JAVA, and I need to format:

So, apparently, it takes out the spaces I added. lol I need the $ to line up for each number. If you understand what I'm saying.. I also need them to only show 2 decimal places.

Bill Robinson
Gross Amount: $3575
Federal Tax: $536.25
State Tax: $125.12500000000001
Social Security Tax: $205.5625
Medicare/Medicaid Tax: $98.3125
Pension Plan: $178.75
Health Insurance: $75.0
Net Pay: $2356.0

to look like :

Bill Robinson
Gross Amount: $3575.00
Federal Tax: $536.25
State Tax: $125.13
Social Security Tax: $205.56
Medicare/Medicaid Tax $98.31
Pension Plan: $178.75
Health Insurance: $75.00
Net Pay: $2356.00

This is my current code:
outFile.println(name);
outFile.println("Gross Amount: $" + grossAmount);
outFile.println("Federal Tax: $" + fTax);
outFile.println("State Tax: $" + sTax);
outFile.println("Social Security Tax: $" + ssTax);
outFile.println("Medicare/Medicaid Tax: $" + mmTax);
outFile.println("Pension Plan: $" + pPlan);
outFile.println("Health Insurance: $" + HI);
outFile.println("Net Pay: $" + netPay);

Thanks in advance for any help you can give. I seen in my book how to do this, but didn't quite understand it. Maybe after seeing this example, I'll understand it better.

This post was edited by ben_graham7 on Mar 3 2013 05:27pm
Member
Posts: 2,579
Joined: Jun 1 2012
Gold: 1,524.00
Mar 3 2013 05:54pm
Use tabs ("\t" in your printlines to align correctly; you may need more than one per line)

Use NumberFormat to format your currencies:
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/NumberFormat.html
Member
Posts: 6,106
Joined: Jun 22 2008
Gold: 116.80
Mar 3 2013 06:04pm
The examples in the book are like:

input: System.out.printf("%5d %n", num);

output: __num
Member
Posts: 224
Joined: Jan 14 2008
Gold: 19,270.00
Mar 6 2013 05:48pm
printtf ist different to println!

what you are looking for is
Code
printf("Euro %.2f", 34.565);

which prints:
Code
Euro 34.57

but this will work with "System.out." and print it to the console. If you want to write it to a File you should use a logger and pass the log to a FileWriter...

I am not quite sure what this is for but if you want to use output on console I suggest using arrays.
Something like:
Code

String name = "Bob the Builder";
String[] strings = {"Gross Amount", "Federal Tax", "State Tax", "Social Security Tax",
"Medicare/Medicaid Tax", "Pension Plan", "Health Insurance", "Net Pay"};
double[] numbers = {3575, 536.25, 125.12500000000001, 205.5625, 98.3125, 178.75, 75.0, 2356.0};

System.out.println(name);
for(int i=0;i<strings.length;i++){
System.out.printf(strings[i] + ": $ %.2F", numbers[i]);
}
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll