org.javamoney.moneta.Money Java Examples

The following examples show how to use org.javamoney.moneta.Money. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JavaMoneyUnitManualTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenAmounts_whenStringified_thanEquals() {
    CurrencyUnit usd = Monetary.getCurrency("USD");
    MonetaryAmount fstAmtUSD = Monetary
      .getDefaultAmountFactory()
      .setCurrency(usd)
      .setNumber(200)
      .create();
    Money moneyof = Money.of(12, usd);
    FastMoney fastmoneyof = FastMoney.of(2, usd);

    assertEquals("USD", usd.toString());
    assertEquals("USD 200", fstAmtUSD.toString());
    assertEquals("USD 12", moneyof.toString());
    assertEquals("USD 2.00000", fastmoneyof.toString());
}
 
Example #2
Source File: AmountsUseExtensionPoints.java    From javamoney-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String... args){

        MonetaryAmount amt = Money.of(1234.56234, "CHF");
        ConsoleUtils.printDetails("Base", amt);
        ConsoleUtils.printDetails("10.5 %", amt.with(MonetaryOperators.percent(10.5)));
        ConsoleUtils.printDetails("10.5 o/oo", amt.with(MonetaryOperators.permil(10.5)));
        ConsoleUtils.printDetails("Major Part", amt.with(MonetaryOperators.majorPart()));
        ConsoleUtils.printDetails("Minor Part", amt.with(MonetaryOperators.minorPart()));
        ConsoleUtils.printDetails("1/Base (Reciprocal)", amt.with(MonetaryOperators.reciprocal()));

        System.out.println("Minor Part as long -> " + amt.query(MonetaryQueries.extractMinorPart()));
        System.out.println("Major Part as long -> " + amt.query(MonetaryQueries.extractMajorPart()));

        ConsoleUtils.printDetails("Rounded (default)", amt.with(Monetary.getDefaultRounding()));
        ConsoleUtils.printDetails("Rounded (DOWN, 1 fraction digit)", amt.with(Monetary.getRounding(
                RoundingQueryBuilder.of().set(RoundingMode.DOWN).setScale(1).build()
        )));
    }
 
Example #3
Source File: AmountEntry.java    From javamoney-examples with Apache License 2.0 6 votes vote down vote up
public void setAmount(MonetaryAmount amount) {
	if (amount != null) {
		codeBox.getSelectionModel().select(
				amount.getCurrency().getCurrencyCode());
		if (FastMoney.class.equals(amount.getClass())) {
			numberType.getSelectionModel().select("Long");
		} else {
			numberType.getSelectionModel().select("BigDecimal");
		}
		numberValue.setText(Money.from(amount).getNumber()
				.toString());
	} else {
		codeBox.getSelectionModel().clearSelection();
		numberType.getSelectionModel().clearSelection();
		numberValue.setText("0");
	}
}
 
Example #4
Source File: PresentValueContinuousCompoundingTest.java    From javamoney-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Method: of(Rate rate, int periods)
 *
 * @throws Exception the exception
 */
@Test
public void testOfAndApply() throws Exception {
    Money money = Money.of(100, "CHF");
    MonetaryOperator rounding = Monetary.getRounding(RoundingQueryBuilder.of().setScale(2).set(RoundingMode.HALF_EVEN)
            .build());
    assertEquals(Money.of(BigDecimal.valueOf(95.12), "CHF"), money.with(PresentValueContinuousCompounding.of(RateAndPeriods.of(0.05, 1))).with(rounding));
    assertEquals(Money.of(BigDecimal.valueOf(90.48), "CHF"), money.with(PresentValueContinuousCompounding.of(RateAndPeriods.of(0.05, 2))).with(rounding));
    assertEquals(Money.of(BigDecimal.valueOf(46.3), "CHF"), money.with(PresentValueContinuousCompounding.of(RateAndPeriods.of(0.07, 11))).with(rounding));

    assertEquals(Money.of(BigDecimal.valueOf(100.00), "CHF"), money.with(PresentValueContinuousCompounding.of(RateAndPeriods.of(0.05, 0))).with(rounding));
    assertEquals(Money.of(BigDecimal.valueOf(100.00), "CHF"), money.with(PresentValueContinuousCompounding.of(RateAndPeriods.of(-0.05, 0))).with(rounding));

    assertEquals(Money.of(BigDecimal.valueOf(105.13), "CHF"), money.with(PresentValueContinuousCompounding.of(RateAndPeriods.of(-0.05, 1))).with(rounding));
    assertEquals(Money.of(BigDecimal.valueOf(110.52), "CHF"), money.with(PresentValueContinuousCompounding.of(RateAndPeriods.of(-0.05, 2))).with(rounding));
    assertEquals(Money.of(BigDecimal.valueOf(215.98), "CHF"), money.with(PresentValueContinuousCompounding.of(RateAndPeriods.of(-0.07, 11))).with(rounding));
}
 
Example #5
Source File: OFXTransactionExtracter.java    From javamoney-examples with Apache License 2.0 6 votes vote down vote up
/**
 * This method extracts and returns the next transaction from the stream. If
 * there are no more transactions in the stream, then null is returned.
 * 
 * @param stream
 *            The input stream that has the transactions.
 * 
 * @return The next transaction or null if there are no more transactions in
 *         the stream.
 * 
 * @throws Exception
 *             If an error occurs.
 */
@Override
protected Transaction next(BufferedReader stream) throws Exception {
	PushbackReader reader = new PushbackReader(stream, 32);
	Transaction trans = null;
	String tag = null;

	while ((tag = getNextTag(reader)) != null) {
		if (tag.equals(TRANSACTION_START) == true) {
			trans = getNextTransaction(reader);
			break;
		} else if (tag.equals(ACCOUNT_BALANCE) == true) {
			String value = getNextValue(reader);

			value = removeNonmoneyValues(value);
			setAccountBalance(Money.of(getCurrencyFormat(value)
					.parse(value), UI_CURRENCY_SYMBOL.getCurrency()));
		}
	}

	return trans;
}
 
Example #6
Source File: AmountsDoCalculations.java    From javamoney-examples with Apache License 2.0 6 votes vote down vote up
/**
   * @param args
   */
  public static void main(String[] args) {
      MonetaryAmount amount = Monetary.getDefaultAmountFactory().setCurrency("EUR").setNumber(234).create();
      ConsoleUtils.printDetails(amount);

      amount = Monetary.getAmountFactory(FastMoney.class).setCurrency("EUR").setNumber(234).create();
      ConsoleUtils.printDetails(amount);

      amount = Monetary.getAmountFactory(
                 MonetaryAmountFactoryQueryBuilder.of().setMaxScale(50).setPrecision(30).build())
                   .setCurrency("EUR").setNumber(234).create();
      ConsoleUtils.printDetails(amount);

Money amt1 = Money.of(10.1234556123456789, "USD");
FastMoney amt2 = FastMoney.of(123456789, "USD");

Money total = amt1.add(amt2).multiply(0.5)
              .remainder(1);
      ConsoleUtils.printDetails(total);
  }
 
Example #7
Source File: JavaMoneyUnitManualTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenAmounts_whenSummed_thanCorrect() {
    List<MonetaryAmount> monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));

    Money sumAmtCHF = (Money) monetaryAmounts
      .stream()
      .reduce(Money.of(0, "CHF"), MonetaryAmount::add);

    assertEquals("CHF 111.35", sumAmtCHF.toString());
}
 
Example #8
Source File: IMFHistoricRateProviderTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnsSameBrazilianValue() {
    CurrencyConversion currencyConversion = provider
            .getCurrencyConversion(BRAZILIAN_REAL);
    assertNotNull(currencyConversion);
    MonetaryAmount money = Money.of(BigDecimal.TEN, BRAZILIAN_REAL);
    MonetaryAmount result = currencyConversion.apply(money);

    assertEquals(result.getCurrency(), BRAZILIAN_REAL);
    assertEquals(result.getNumber().numberValue(BigDecimal.class),
            BigDecimal.TEN);

}
 
Example #9
Source File: NumericRepresentationTest.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNumberType() throws Exception{
    BigDecimal bd = new BigDecimal("0.1234523");
    MonetaryAmount[] amounts = new MonetaryAmount[]{Money.of(bd, "USD"), FastMoney.of(2334434354L, "CHF")};
    for(MonetaryAmount amount : amounts){
        assertEquals("Invalid number type for " + amount, amount.getNumber().getNumberType(),
                     np.getNumberType(amount));
    }
}
 
Example #10
Source File: ExtractorMajorPartOperatorTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnNegativeValue() {
	CurrencyUnit currency = Monetary.getCurrency("BHD");
	MonetaryAmount money = Money.parse("BHD -1.345");
	MonetaryAmount result = operator.apply(money);
	assertEquals(result.getCurrency(), currency);
	assertEquals(result.getNumber().doubleValue(), -1.0);

}
 
Example #11
Source File: CompoundInterestTest.java    From javamoney-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate zero periods.
 *
 * @throws Exception the exception
 */
@Test
public void calculate_zeroPeriods() throws Exception {
    CompoundInterest ci = CompoundInterest.of(
            RateAndPeriods.of(0.05,0)
    );
    assertEquals(Money.of(10.03,"CHF").with(ci), Money.of(0,"CHF"));
    assertEquals(Money.of(0,"CHF").with(ci), Money.of(0,"CHF"));
    assertEquals(Money.of(-20.45,"CHF").with(ci), Money.of(0,"CHF"));
}
 
Example #12
Source File: PresentValueOfAnnuityTest.java    From javamoney-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Apply.
 *
 * @throws Exception the exception
 */
@Test
public void apply() throws Exception {
    PresentValueOfAnnuity val = PresentValueOfAnnuity.of(
            RateAndPeriods.of(0.08, 10)
    );
    Money m = Money.of(10, "CHF");
    assertEquals(val.apply(m), m.with(val));
}
 
Example #13
Source File: MonetaryFormatsTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void testFormat_BGN_bg_BG() {
    AmountFormatQuery formatQuery = AmountFormatQueryBuilder.of(BULGARIA).set(CODE).build();
    MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(formatQuery);
    assertMoneyFormat(format,  Money.of(123.01, "BGN"), "123,01 BGN");
    assertMoneyFormat(format, Money.of(14000.12, "BGN"), "14 000,12 BGN");
}
 
Example #14
Source File: MonetaryConversionTest.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testMonetaryConversionsECB() {
	final MonetaryAmount amt = Money.of(2000, "EUR");
	CurrencyConversion conv= MonetaryConversions.getConversion("CHF", "ECB");
	MonetaryAmount converted = amt.with(conv);
	assertNotNull(converted);
}
 
Example #15
Source File: ExchangeCurrencyOperatorTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnPositiveValue() {
	MonetaryAmount money = Money.parse("EUR 2.35");
	MonetaryAmount result = operator.apply(money);
	assertEquals(result.getCurrency(), this.real);
	assertEquals(result.getNumber().doubleValue(), 2.35);
}
 
Example #16
Source File: JavaMoneyUnitManualTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenArithmetic_whenStringified_thanEqualsAmount() {
    CurrencyUnit usd = Monetary.getCurrency("USD");

    Money moneyof = Money.of(12, usd);
    MonetaryAmount fstAmtUSD = Monetary
      .getDefaultAmountFactory()
      .setCurrency(usd)
      .setNumber(200.50)
      .create();
    MonetaryAmount oneDolar = Monetary
      .getDefaultAmountFactory()
      .setCurrency("USD")
      .setNumber(1)
      .create();
    Money subtractedAmount = Money
      .of(1, "USD")
      .subtract(fstAmtUSD);
    MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
    MonetaryAmount divideAmount = oneDolar.divide(0.25);

    assertEquals("USD", usd.toString());
    assertEquals("USD 1", oneDolar.toString());
    assertEquals("USD 200.5", fstAmtUSD.toString());
    assertEquals("USD 12", moneyof.toString());
    assertEquals("USD -199.5", subtractedAmount.toString());
    assertEquals("USD 0.25", multiplyAmount.toString());
    assertEquals("USD 4", divideAmount.toString());
}
 
Example #17
Source File: PresentValueOfAnnuityTest.java    From javamoney-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate periods 1.
 *
 * @throws Exception the exception
 */
@Test
public void calculate_Periods1() throws Exception {
    Money m = Money.of(10, "CHF");
    PresentValueOfAnnuity val = PresentValueOfAnnuity.of(
            RateAndPeriods.of(0.05, 1)
    );
    assertEquals(Money.of(9.523809523809524,"CHF").getNumber().doubleValue(),
            m.with(val).getNumber().doubleValue(),0.000001d);
    val = PresentValueOfAnnuity.of(
            RateAndPeriods.of(-0.05, 1)
    );
    assertEquals(Money.of(10.5263157894736842105263,"CHF").getNumber().doubleValue(),
            m.with(val).getNumber().doubleValue(), 0.00001d);
}
 
Example #18
Source File: ExtractorMinorPartQueryTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnMajorPartNegative() {
	MonetaryAmount monetaryAmount = Money.parse("BHD -1.345");
	Long result = query.queryFrom(monetaryAmount);
	Long expected = -345L;
	assertEquals(result, expected);
}
 
Example #19
Source File: ExtractorMajorPartQueryTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnMajorPartPositive() {
	MonetaryAmount monetaryAmount = Money.parse("EUR 2.35");
	Long result = query.queryFrom(monetaryAmount);
	Long expected = 2L;
	assertEquals(result, expected );
}
 
Example #20
Source File: BankAccountJS.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
public BankAccount to() {
	BankAccount account = new BankAccount();
	account.setBegin(LocalDateTime.parse(begin));
	account.setEnd(LocalDateTime.parse(end));
	account.setUser(user);
	account.setValue(Money.parse(value));
	return account;
}
 
Example #21
Source File: StreamFactory.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
public static  Stream<MonetaryAmount> streamNormal() {
	Money m1 = Money.of(BigDecimal.TEN, BRAZILIAN_REAL);
	Money m2 = Money.of(BigDecimal.ZERO, BRAZILIAN_REAL);
	Money m3 = Money.of(BigDecimal.ONE, BRAZILIAN_REAL);
	Money m4 = Money.of(BigDecimal.valueOf(4L), BRAZILIAN_REAL);
	Money m5 = Money.of(BigDecimal.valueOf(5L), BRAZILIAN_REAL);
	return Stream.of(m1, m2, m3, m4, m5);
}
 
Example #22
Source File: BasicsTest.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertAmount() {
    MonetaryAmount converted =
            basics.convertAmount(Money.of(200, "USD"), new BigDecimal("23628732374387462.87638476"), "GBP");
    assertNotNull(converted);
    assertEquals(new BigDecimal("23628732374387462.87638476"),
            converted.getNumber().numberValue(BigDecimal.class).stripTrailingZeros());
    assertEquals("GBP", converted.getCurrency().getCurrencyCode());
}
 
Example #23
Source File: BalloonLoanPaymentTest.java    From javamoney-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate zero periods.
 *
 * @throws Exception the exception
 */
@Test(expected=MonetaryException.class)
public void calculate_zeroPeriods() throws Exception {
    BalloonLoanPayment.of(
            RateAndPeriods.of(0.05,0), Money.of(5, "CHF")
    );
}
 
Example #24
Source File: BalloonLoanPaymentTest.java    From javamoney-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate one periods.
 *
 * @throws Exception the exception
 */
@Test
public void calculate_onePeriods() throws Exception {
    BalloonLoanPayment ci = BalloonLoanPayment.of(
            RateAndPeriods.of(0.05,1), Money.of(5, "CHF")
    );
    assertEquals(Money.of(100,"CHF").with(ci).with(Monetary.getDefaultRounding()),Money.of(100,"CHF"));
    assertEquals(Money.of(0,"CHF").with(ci).with(Monetary.getDefaultRounding()),Money.of(-5,"CHF"));
    assertEquals(Money.of(-1,"CHF").with(ci).with(Monetary.getDefaultRounding()),Money.of(-6.05,"CHF"));
}
 
Example #25
Source File: AmountEntry.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
public MonetaryAmount getAmount() {
	String code = (String) codeBox.getSelectionModel().getSelectedItem();
	String typeClass = (String) numberType.getSelectionModel()
			.getSelectedItem();
	CurrencyUnit currency = Monetary.getCurrency(code);
	BigDecimal dec = new BigDecimal(numberValue.getText());
	if (typeClass != null) {
		if ("Long".equals(typeClass)) {
			return FastMoney.of(dec,currency);
		}
	}
	return Money.of(dec,currency);
}
 
Example #26
Source File: MonetaryAmountFormatTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
    public void testWithCustomPattern() {
        Money money = Money.of(12345.23, "EUR");
//        testCustomFormat(money, "#,##0.## ¤", "12.345,23 EUR", "12.345,23 EUR", CODE);
//        testCustomFormat(money, "#,##0.##¤", "12.345,23EUR", "12.345,23EUR", CODE);
//        testCustomFormat(money, "¤ #,##0.##", "EUR 12.345,23", "EUR 12.345,23", CODE);
//        testCustomFormat(money, "¤#,##0.##", "EUR12.345,23", "EUR12.345,23", CODE);
//        testCustomFormat(money, "LITERAL ¤#,##0.##", "LITERAL EUR12.345,23", "LITERAL EUR12.345,23", CODE);
//        testCustomFormat(money, "LITERAL ¤ #,##0.##", "LITERAL EUR 12.345,23", "LITERAL EUR 12.345,23", CODE);
        testCustomFormat(money, "LITERAL ¤ #,##0.## LITERAL", "LITERAL EUR 12.345,23 LITERAL", "LITERAL EUR 12.345,23 LITERAL", CODE);
        testCustomFormat(money, "LITERAL #,##0.## ¤ LITERAL", "LITERAL 12.345,23 EUR LITERAL", "LITERAL 12.345,23 EUR LITERAL", CODE);
        testCustomFormat(money, "LITERAL #,##0.##¤ LITERAL", "LITERAL 12.345,23EUR LITERAL", "LITERAL 12.345,23EUR LITERAL", CODE);
    }
 
Example #27
Source File: LongColumnMoneyMajorMapper.java    From jadira with Apache License 2.0 5 votes vote down vote up
@Override
public Money fromNonNullString(String s) {
	
	int separator = s.indexOf(' ');
	
	String currency = s.substring(0, separator);
	String value = s.substring(separator + 1);

	Monetary.getCurrency(currency);
	return Money.of(Long.parseLong(value), Monetary.getCurrency(currency));
}
 
Example #28
Source File: ECBCurrentRateProviderTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConvertsEuroToDollar() {
    CurrencyConversion currencyConversion = provider
            .getCurrencyConversion(DOLLAR);
    assertNotNull(currencyConversion);
    MonetaryAmount money = Money.of(BigDecimal.TEN, EURO);
    MonetaryAmount result = currencyConversion.apply(money);

    assertEquals(result.getCurrency(), DOLLAR);
    assertTrue(result.getNumber().doubleValue() > 0);

}
 
Example #29
Source File: SmokeTest.java    From javamoney-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateAmounts() {
    // Creating one
    CurrencyUnit currency = Monetary.getCurrency("CHF");
    Money amount1 = Money.of(1.0d, currency);
    Money amount2 = Money.of(1.0d, currency);
    Money amount3 = amount1.add(amount2);
    logger.debug(amount1 + " + " + amount2 + " = " + amount3);
    assertEquals(1.0d, amount1.getNumber().doubleValue(), 0);
    assertEquals(1.0d, amount2.getNumber().doubleValue(), 0);
    assertEquals(2.0d, amount3.getNumber().doubleValue(), 0);
}
 
Example #30
Source File: BalloonLoanPaymentTest.java    From javamoney-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Of correct balloon amount.
 *
 * @throws Exception the exception
 */
@Test
public void of_correctBalloonAmount() throws Exception {
    BalloonLoanPayment ci = BalloonLoanPayment.of(
            RateAndPeriods.of(0.05,1), Money.of(5, "CHF")
    );
    assertEquals(ci.getBalloonAmount(),  Money.of(5, "CHF"));
    ci = BalloonLoanPayment.of(
            RateAndPeriods.of(0.05,234), Money.of(11, "CHF")
    );
    assertEquals(ci.getBalloonAmount(),  Money.of(11, "CHF"));
}