0

The purpose of this program is to give correct change. For Example:

Input: $45.54

Output: 4 Ten Dollar Bills, 1 Five Dollar Bills, 2 Quarters, 4 Pennies.

Now onto my question:

I want to display a BigDecimal as an integer without losing the original value, as I have to continue my division all the way down until i get to 0.01 for pennies.

My Current Code looks like:

    BigDecimal tenDollar = BigDecimal.valueOf(10);
    BigDecimal tenDollarNext;
    BigDecimal fiveDollar = BigDecimal.valueOf(5);
    BigDecimal fiveDollarNext;

/* Get Input From User */

    System.out.print("Please enter the amount to be converted: ");
   Scanner scan = new Scanner(System.in);
    BigDecimal money = scan.nextBigDecimal();

    NumberFormat usdFormat = NumberFormat.getCurrencyInstance(Locale.US);
    usdFormat.setMinimumFractionDigits(2);
    usdFormat.setMaximumFractionDigits(2);

    System.out.println("Amount you entered: " + usdFormat.format(money));

    /* Begin Processing and Displaying Information */

    tenDollarNext = money.divide(tenDollar);
    System.out.println(tenDollarNext + " Ten Dollar Bills");

    fiveDollarNext = tenDollarNext.divide(fiveDollar, 0, RoundingMode.FLOOR);
    System.out.println(fiveDollarNext + " Five Dollar Bills");

Which ends up Displaying:

Please enter the amount to be converted: 45.54
Amount you entered: $45.54
4.554 Ten Dollar Bills
0 Five Dollar Bills

My goal is to have the 4.554 be displayed as 4 without losing the decimal places at the end for the calculation. I'm sure there is a simple answer to this, I was hoping someone could either tell me the conversion for it or point me in the direction of where I could find the answer. None of my search queries have been helpful.

Zach Davis
  • 27
  • 1
  • 5

1 Answers1

2

Use the divideToIntegralValue method of the BigDecimal class, in place of divide. This returns a BigDecimal whose value is an integer. You can then subtract the appropriate amount from money and continue on.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110