Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Calculator {
- private final DecimalFormat df;
- public Calculator() {
- this.df = new DecimalFormat("#.##");
- }
- public double convert(Currency from, Currency to, double fromAmount) {
- if (!(from instanceof Currency) || (to instanceof Currency)) {
- throw new IllegalArgumentException(
- "Object 'other' not instance of class 'Currency'");
- }
- if (fromAmount <= 0) {
- throw new IllegalArgumentException("Amount cannot be less than 0!");
- }
- if (from == to) {
- return fromAmount;
- }
- double amountInNOK = 0;
- double toAmount = 0;
- if (from.getUnit() == 100 && to.getUnit() == 100) {
- amountInNOK = fromAmount * (from.getRate() / 100);
- toAmount = amountInNOK * (to.getRate() / 100);
- } else if (from.getUnit() == 1 && to.getUnit() == 1) {
- amountInNOK = fromAmount * from.getRate();
- toAmount = amountInNOK * to.getRate();
- } else if (from.getUnit() == 1 && to.getUnit() == 100) {
- amountInNOK = fromAmount * from.getRate();
- toAmount = amountInNOK * (to.getRate() / 100);
- } else { // from.getUnit() == 100 && to.getUnit() == 1
- amountInNOK = fromAmount * (from.getRate() / 100);
- toAmount = amountInNOK * to.getRate();
- }
- return Double.parseDouble(df.format(toAmount));
- }
- }
Add Comment
Please, Sign In to add comment