How to replace monies in dual java with BigDecimal

I'm doing a college job. I use double money I know that double currency values are not recommended, so I want to know how to replace the existing code I double with BigDecimal

Since this is a college assignment, I don't want to help my code directly or publish it here, so I created the following code. I want to reply directly, that is, change the code I provided so that I can understand what happened

I want to know how BigDecimal multiplies / divides / adds / subtracts with int or double, or even by chance

There are other topics related to the use of BigDecimal, but they do not cover my specific questions, but I'm sorry if I ignore the posts I have answered

This is 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 use long for all calculations, just insert a decimal point at the end

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>