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

标签 java

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

相关文章:

java - 去除语料库中出现次数少的词的算法

java - Java 日期格式问题

java - 重用 HttpURLConnection

java - 如何使用 Netty 在单个端口上编写多协议(protocol)处理程序?

java - 如何使用 dagger 2 才能使用共享首选项的抽象表示?

java - 需要使用 lambda 映射多个文件中的归约行

java - 您如何为您的 Java Web 应用程序自动化 Javascript 缩小?

java - 如何从具有单例类的类对象中获取正确的值?

java - EJB 3 + JPA2 = 具有空字段的反序列化对象

java - react 堆项目 : Multiple Publishers making HTTP calls and one Subscriber to handle all results