Nico
Nico

Reputation: 3489

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)));
    }
}

Upvotes: 3

Views: 561

Answers (3)

rossum
rossum

Reputation: 15693

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

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533740

If you want to avoid using double, you need to not use it from the start.

BigDecimal money1 = new BigDecimal(in.nextLine());

You should be able to see that the result is exactly the same after rounding.

Upvotes: 3

Kylar
Kylar

Reputation: 9334

BigDecimals are immutable, but you can create new ones with specific calls:

BigDecimal two = new BigDecimal("2.00");
BigDecimal four = new BigDecimal("4.00");

BigDecimal result = four.divide(two);

You'll probably also want to look at the scale() methods.

Upvotes: 1

Related Questions