utkarsh dubey utkarsh dubey - 1 year ago 128
Java Question

How to display values only upto 2 decimal places double in java

I am doing this java question :

Jalaj purchased a table for Rs.200.4 and due to some scratches on its
top he had to sell it for Rs.176.5. Find his loss and loss%.

LOSS : Cost Price - Selling Price

LOSS% : (LOSS/Cost Price)*100

a. Declare four double variables i.e. costprice, sellingPrice, loss,

b. Assign 200.4 to costPrice and 176.5 to sellingPrice.

c. Print loss and lossPercentage according to the given formulas like:
823.67 8.23 d.

For printing upto two decimal places use

System.out.printf("%.2f\n", loss);


  1. output for both should be upto two decimal places

  2. Output should be displayed in two different lines

My code:

/*Write your code here */
import java.util.Scanner;
class bkws{
public static void main(String args[]){
double costPrice,sellingPrice,loss,lossPercentage;

Now I am thinking of using
but for rounding off to 2 decimal plas it should be:


But it is giving error and I also want to know that if there is any easy way to round off to
decimal places without using
in java

Answer Source

printf with an f for format at the end is a different method to print or println

For printing upto two decimal places use

System.out.printf("%.2f\n", loss);

BTW: Using %n inside a format string is a better choice than \n as %n is platform independent.

You don't need to round the result if you using rounding in the format.

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