1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/task1/solution06/src/org/apidesign/apifest08/currency/Amount.java Sun Sep 28 14:12:38 2008 +0200
1.3 @@ -0,0 +1,80 @@
1.4 +package org.apidesign.apifest08.currency;
1.5 +
1.6 +import java.math.BigDecimal;
1.7 +import java.math.RoundingMode;
1.8 +import java.util.Currency;
1.9 +import static org.apidesign.apifest08.currency.Assert.*;
1.10 +
1.11 +/**
1.12 + * An amount representation. Amount is represented as composition of a value and
1.13 + * a currency.
1.14 + */
1.15 +public final class Amount {
1.16 +
1.17 + private final BigDecimal value;
1.18 + private final Currency currency;
1.19 + private final int scale;
1.20 + private final RoundingMode roundingMode;
1.21 +
1.22 + public static final RoundingMode DEFAULT_ROUNDING = RoundingMode.HALF_EVEN;
1.23 +
1.24 + public Amount(final BigDecimal value, final Currency currency) {
1.25 + notNull(value, "value");
1.26 + notNull(currency, "currency");
1.27 + this.value = value;
1.28 + this.currency = currency;
1.29 + this.scale = currency.getDefaultFractionDigits();
1.30 + this.roundingMode = DEFAULT_ROUNDING;
1.31 + }
1.32 +
1.33 + public Amount(final BigDecimal value, final Currency currency, final RoundingMode roundingMode) {
1.34 + notNull(value, "value");
1.35 + notNull(currency, "currency");
1.36 + notNull(roundingMode, "roundingMode");
1.37 +
1.38 + this.value = value;
1.39 + this.currency = currency;
1.40 + this.scale = currency.getDefaultFractionDigits();
1.41 + this.roundingMode = roundingMode;
1.42 + }
1.43 +
1.44 + public Amount(final long value, final Currency currency) {
1.45 + this(BigDecimal.valueOf(value), currency);
1.46 + }
1.47 +
1.48 + public Amount(final String value, final Currency currency) {
1.49 + this(new BigDecimal(value), currency);
1.50 + }
1.51 +
1.52 + /**
1.53 + * @return the value with scale of the associated currency and rounded by
1.54 + * the rounding mode.
1.55 + */
1.56 + public BigDecimal getValue() {
1.57 + return value.setScale(scale, roundingMode);
1.58 + }
1.59 +
1.60 + /**
1.61 + * @return the raw (no explicit scale, no explicit rounding) value
1.62 + */
1.63 + public BigDecimal getRawValue() {
1.64 + return value;
1.65 + }
1.66 +
1.67 + public Currency getCurrency() {
1.68 + return currency;
1.69 + }
1.70 +
1.71 + public int getScale() {
1.72 + return scale;
1.73 + }
1.74 +
1.75 + public RoundingMode getRoundingMode() {
1.76 + return roundingMode;
1.77 + }
1.78 +
1.79 + @Override
1.80 + public String toString() {
1.81 + return value + ",- " + currency.toString();
1.82 + }
1.83 +}