我正在做这个Java问题:
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:
output for both should be upto two decimal places
Output should be displayed in two different lines
我的代码:
/*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);
}
}
现在我正在考虑使用Math.round
但四舍五入到小数点后两位应该是:
Math.round(number*100)/100;
但是它给出了错误,我也想知道是否有任何简单的方法可以四舍五入到 n
不使用小数位 Math.round
在Java中。
最佳答案
double costPrice,sellingPrice,loss,lossPercentage;
costPrice=200.4;
sellingPrice=176.5;
loss=costPrice-sellingPrice;
lossPercentage=(loss/costPrice)*100;
System.out.println(String.format("%.2f", loss));
System.out.println(String.format("%.2f", lossPercentage));
或者
double costPrice,sellingPrice,loss,lossPercentage;
costPrice=200.4;
sellingPrice=176.5;
loss=costPrice-sellingPrice;
lossPercentage=(loss/costPrice)*100;
loss = (int)Math.round(loss * 100)/(double)100;
lossPercentage = (int)Math.round(lossPercentage * 100)/(double)100;
System.out.println(loss);
System.out.println(lossPercentage);
关于java - 如何在java中仅显示小数点后两位的 double 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39448384/