猿问

BigDecimal setScale方法语法不起作用

这段代码在我提到setScale()的那一行上给了我一个错误;我说“需要舍入”给我一个错误。我正在尝试制作一个将使用cp和sp的应用程序,然后根据利润/亏损找到利润/亏损百分比。有人可以用BigDecimal语句帮助我吗?


```java

import java.math.BigDecimal;

import java.math.RoundingMode;

import java.util.Scanner;


abstract class functions

{

    abstract void cpSP();

}


public class Percentage

{

    static Scanner sc = new Scanner(System.in);

    public void cpSP()

    {

        System.out.println("Enter the Cost Price:");

        double CP = sc.nextDouble();

        System.out.println("Enter the Selling Price:");

        double SP = sc.nextDouble();

        if (CP > SP)

        {

            System.out.println("As the Cost Price is greater than the Selling Price, there will be LOSS.");

            System.out.println("Loss = CP - SP");

            double loss = CP - SP;

            System.out.println("Loss = " + loss);

            System.out.println("Now,");

            System.out.println("Loss percentage = Loss/CP x 100");

            System.out.println("");

            double lossPercentage = (loss/CP)*100;

            String lPString = Double.toString(lossPercentage);

            BigDecimal bd = new BigDecimal(lPString);

            bd.setScale(2);

            System.out.println("Loss percentage = " + bd + "%" );

        }

        else if (SP > CP) 

        {

            System.out.println("As the Cost Price is less than the Selling Price, there will be PROFIT.");

            System.out.println("Profit = SP - CP");

            double profit = SP - CP;

            System.out.println("Profit = " + profit);

            System.out.println("Now,");

            System.out.println("Profit percentage = Profit/CP x 100");

            double profitPercentage = (profit / CP)*100;

            String pPString = Double.toString(profitPercentage);

            BigDecimal bd = new BigDecimal(pPString).setScale(2, RoundingMode.UNNECESSARY);

            System.out.println("Proft percentage = " + bd + "%" );

        }

        else

        {

            System.out.println("No profit, no loss.");

        }

    }




烙印99
浏览 419回答 1
1回答

侃侃尔雅

该setScale方法的javadoc中已明确提及如果{@code roundingMode == ROUND_UNNECESSARY}和指定的缩放操作需要四舍五入,则@throws ArithmeticException。示例:这将引发以上异常new BigDecimal("1200.1234").setScale(2, BigDecimal.ROUND_UNNECESSARY)因为当您将其比例缩小为2时,您需要指定舍入的方式-向上舍入(1200.13)或向下舍入(1200.12)如果仅需要两位小数,请选择一种舍入模式(您可以接受的任何一种)
随时随地看视频慕课网APP

相关分类

Java
我要回答