utkarsh dubey - 1 month ago 15x
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,
lossPercentage

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);

Note:

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;
costPrice=200.4;
sellingPrice=176.5;
loss=costPrice-sellingPrice;
lossPercentage=(loss/costPrice)*100;
System.out.print("%.2f",loss);
System.out.println("%.2f",lossPercentage);
}
}
``````

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

``````Math.round(number*100)/100;
``````

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

`printf` with an `f` for format at the end is a different method to `print` or `println`
BTW: Using `%n` inside a format string is a better choice than `\n` as `%n` is platform independent.