javadoubleroundingdecimalformat

Round off a double variable to different decimal digits depending on another variable's decimal place (JAVA)


Here is my simplified code

public void compute{
 Scanner scan = new Scanner(System.in);
 double BUY=0;
 double RATE, AMOUNT;
 System.out.println("Enter Rate: ");
 RATE = scan.nextDouble();
 System.out.println("Enter Amount: ");
 AMOUNT = scan.nextDouble();
 BUY = (RATE*AMOUNT)+BUY;
}

Basically, I want the variable BUY to round off and have the same decimal digit as the variable RATE, but RATE can have different decimal digits depending on what the user entered so the decimal digits of RATE need to keep changing

For example, user entered

RATE = 52.38 //has 2 decimal digits

AMOUNT = 45.53

If we do the BUY=(RATE*AMOUNT)+BUY

BUY will be BUY=2,384.8614 //has 4 decimal but should be 2 like RATE, and also knowing double, it'll probably show about 15 decimal digits

If user want to try again and entered

RATE = 65.879 // has 3 decimal digits

BUY should also then have 3 decimal digits

How can I make BUY adapt to decimal digits of RATE


Solution

  • Well, question is still not clear if you want to round off or print upto decimal places as that of RATE. But here is solution which will display same number of digits as that RATE:

            Scanner scan = new Scanner(System.in);
            double BUY = 0;
            double RATE, AMOUNT;
            System.out.println("Enter Rate: ");
            RATE = scan.nextDouble();
            int newScale=String.valueOf(RATE).split("[.]")[1].length(); //extract total number of digits
            
            System.out.println("Enter Amount: ");
            AMOUNT = scan.nextDouble();
            BUY = (RATE * AMOUNT) + BUY;
            System.out.println(BUY%2);
            System.out.println(new 
            BigDecimal(BUY).setScale(newScale,RoundingMode.HALF_EVEN)); // display BUY value with exactly same number of digits as that of RATE
    
            BUY =  new BigDecimal(BUY).setScale(newScale,RoundingMode.HALF_EVEN).doubleValue();  // converting bigdecimal to double
            System.out.println(BUY);  // printing double value.
    

    Here, I am extracting total number of digits from RATE & then later using it as scale for printing BUY value.

    Edit : you can use .doubleValue(); function to convert bigdecimal to double as added in above code.