gpt4 book ai didi

java - 如何在java中仅显示小数点后两位的 double 值

转载 作者:行者123 更新时间:2023-12-02 03:22:18 25 4
gpt4 key购买 nike

我正在做这个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:

  1. output for both should be upto two decimal places

  2. 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com