Search code examples
javacurrencybigdecimal

How to replace doubles with BigDecimal for monies in java


I am doing a college assignment where I have used doubles for money. I know it is not advisable to use doubles for monetary values so I am wondering how I can replace my existing code that has doubles with BigDecimal.

Since it is a college assignment, I didn't want direct help on my code and didn't want to post it here either, so I have created the following code to which I would appreciate direct replies, i.e. change the code I am providing so that I can understand what's going on.

I am wondering how BigDecimal can be multiplied/divided/added/subtracted with an int or a double or if that isn't even a possiblity.

There are other topics covering BigDecimal usage but they don't cover my specific question, however, I apologize if I have overlooked a post where it has already been answered.

Here's the code:

import java.util.Scanner;
import java.text.NumberFormat;

class example {
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    NumberFormat fm = NumberFormat.getCurrencyInstance();

    System.out.println("Enter the first amount:");
    double money1 = in.nextDouble();
    System.out.println("Enter the second amount:");
    double money2 = in.nextDouble();
    System.out.println("Enter the third amount:");
    double money3 = in.nextDouble();

    double tax = 0.2;
    double totalmoney = money1 + money2 + money3;
    double moneytax = (totalmoney)*tax;


    System.out.println("Your money added together is: " + fm.format(totalmoney));
    System.out.println("Tax on your money is: " + fm.format(moneytax));
    System.out.println("Your money after tax deduction is: " + fm.format((totalmoney-moneytax)));
    }
}

Solution

  • An alternative to BigDecimal might be to do all calculations in cents, using longs, and just insert the decimal point right at the end.