MickeyMoise
MickeyMoise

Reputation: 259

I cant add a dollar sign after the formatted number (Java)

I cant seem to figure out why this code keeps giving me errors related to formatting when i try to reduce the numbers to the second decimal point, while also adding a "$" after them.

Scanner scan = new Scanner(System.in);
int months = scan.nextInt();
int waterPrice = 20;
int internetPrice = 15;
int water = months * waterPrice;
int internet = months * internetPrice;
double others = 0;
double electricity = 0;
double electricityPrice;

for(int i=0; i<months; i++){
    electricityPrice = scan.nextDouble();
    electricity += electricityPrice;
    others = (electricity + water + internet) + 0.2 * (electricity + water + internet);

}
double avarage = (electricity + water + internet + others)/5;

System.out.println("Electricity: %.2f$$"+ electricity);
System.out.printf("Water: %.2d$$", water);
System.out.printf("Internet: %.2d$$", internet);
System.out.printf("Other: %.2f$$", others);
System.out.printf("Average: %.2f$$", avarage);        

Upvotes: 0

Views: 398

Answers (2)

Nitin Bisht
Nitin Bisht

Reputation: 5361

Try:

System.out.format("Electricity: %.2f $$\n", 234.5554);

or

System.out.printf("Electricity: %.2f $$\n", 234.5554);

Output:

enter image description here

In your case:

System.out.printf("Electricity: %.2f$$\n", electricity);
System.out.printf("Water: %d$$\n", water);
System.out.printf("Internet: %d$$\n", internet);
System.out.printf("Other: %.2f$$\n", others);
System.out.printf("Average: %.2f$$\n", avarage);

Output:

enter image description here

Note: In your case I have replaced %.2d with %d because water and internet are of integer type. If you want decimal precision for all i.e. 100.00 $$ then you need to replace int with double and use System.out.printf(%.2f$$\n)

Upvotes: 3

ajayg2808
ajayg2808

Reputation: 375

You are using System.out.println() which is not useful for formatted output. it will concatenate output to single string and display it.

For formatted output like you want go with Syatem.out.printf() which is similar to C printf() function.

You can also use String.format() for formatted output.

Example:

Syatem.out.printf("Electricity: %.2f$$", electricity)
System.out.println("Electricity: " + String.format("%.2f$$", electricity))

Upvotes: 1

Related Questions