Java Code Examples for javax.money.MonetaryAmount

The following examples show how to use javax.money.MonetaryAmount. These examples are extracted from open source projects. 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
public static void main(String[] args) {
	List<MonetaryAmount> orderCurrency = getDollars().stream().sorted(MonetaryFunctions.sortCurrencyUnit()).collect(Collectors.toList());
	List<MonetaryAmount> orderSort = getDollars()
			.stream()
			.sorted(MonetaryFunctions.sortCurrencyUnit().thenComparing(
					MonetaryFunctions.sortNumber()))
			.collect(Collectors.toList());
	List<MonetaryAmount> orderCurrencyNumber = getDollars()
			.stream()
			.sorted(MonetaryFunctions.sortCurrencyUnit().thenComparing(
					MonetaryFunctions.sortCurrencyUnitDesc()))
			.collect(Collectors.toList());
	
	System.out.println(orderCurrency);
	System.out.println(orderSort);
	System.out.println(orderCurrencyNumber);
	
}
 
Example 2
Source Project: javamoney-examples   Source File: ConversionExample.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String... args) {
	String termCurrencyCode = DEFAULT_TERM_CURRENCY_CODE;
	if (args.length > 0) {
		termCurrencyCode = args[0];
	}
	final MonetaryAmount amt = Money.of(2000, "EUR");
	CurrencyConversion conv= MonetaryConversions.getConversion(termCurrencyCode, "ECB");
	System.out.println(MessageFormat.format("2000 EUR (ECB)-> {0} = {1}",
			termCurrencyCode, amt.with(conv)));
	conv= MonetaryConversions.getConversion(termCurrencyCode, "IMF");
	System.out.println(MessageFormat.format("2000 EUR (IMF)-> {0} = {1}",
			termCurrencyCode, amt.with(conv)));

	System.out.println(MessageFormat.format(
			"2000 EUR (ECB, at 5th Jan 2015)-> {0} = {1}",
			termCurrencyCode, amt.with(MonetaryConversions
					.getConversion(ConversionQueryBuilder.of()
							.setTermCurrency(termCurrencyCode)
							.set(LocalDate.of(2015, 01, 05)).build()))));
}
 
Example 3
Source Project: jsr354-ri   Source File: ECBHistoric90RateProviderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = MonetaryException.class)
public void shouldSetTimeInLocalDateTime() {

	LocalDate localDate = YearMonth.of(2014, Month.JANUARY).atDay(9);

	ConversionQuery conversionQuery = ConversionQueryBuilder.of()
                       .setTermCurrency(EURO).set(localDate).build();
	CurrencyConversion currencyConversion = provider
			.getCurrencyConversion(conversionQuery);
	assertNotNull(currencyConversion);
	MonetaryAmount money = Money.of(BigDecimal.TEN, DOLLAR);
	MonetaryAmount result = currencyConversion.apply(money);

	assertEquals(result.getCurrency(), EURO);
	assertTrue(result.getNumber().doubleValue() > 0);
}
 
Example 4
Source Project: salespoint   Source File: Totalable.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link Totalable} for the given {@link Iterable} of {@link Priced} elements.
 * 
 * @param priced must not be {@literal null}.
 * @return
 */
static <T extends Priced> Totalable<T> of(Iterable<T> priced) {

	Assert.notNull(priced, "Priced must not be null!");

	return new Totalable<T>() {

		/* 
		 * (non-Javadoc)
		 * @see org.salespointframework.order.Totalable#getTotal()
		 */
		@Override
		public MonetaryAmount getTotal() {
			return Priced.sumUp(priced);
		}

		@Override
		public Iterator<T> iterator() {
			return priced.iterator();
		}
	};
}
 
Example 5
Source Project: tutorials   Source File: JavaMoneyUnitManualTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenAmount_whenCustomFormat_thanEquals() {
    MonetaryAmount oneDollar = Monetary
      .getDefaultAmountFactory()
      .setCurrency("USD")
      .setNumber(1)
      .create();

    MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
      .of(Locale.US)
      .set(CurrencyStyle.NAME)
      .set("pattern", "00000.00 US Dollar")
      .build());
    String customFormatted = customFormat.format(oneDollar);

    assertNotNull(customFormat);
    assertEquals("USD 1", oneDollar.toString());
    assertEquals("00001.00 US Dollar", customFormatted);
}
 
Example 6
Source Project: jackson-datatype-money   Source File: MoneyModule.java    License: MIT License 6 votes vote down vote up
private MoneyModule(final AmountWriter<?> writer,
        final FieldNames names,
        final MonetaryAmountFormatFactory formatFactory,
        final MonetaryAmountFactory<? extends MonetaryAmount> amountFactory,
        final MonetaryAmountFactory<FastMoney> fastMoneyFactory,
        final MonetaryAmountFactory<Money> moneyFactory,
        final MonetaryAmountFactory<RoundedMoney> roundedMoneyFactory) {

    this.writer = writer;
    this.names = names;
    this.formatFactory = formatFactory;
    this.amountFactory = amountFactory;
    this.fastMoneyFactory = fastMoneyFactory;
    this.moneyFactory = moneyFactory;
    this.roundedMoneyFactory = roundedMoneyFactory;
}
 
Example 7
private Formatter<MonetaryAmount> configureFormatterFrom(NumberFormat annotation) {
	if (StringUtils.hasLength(annotation.pattern())) {
		return new PatternDecoratingFormatter(resolveEmbeddedValue(annotation.pattern()));
	}
	else {
		Style style = annotation.style();
		if (style == Style.NUMBER) {
			return new NumberDecoratingFormatter(new NumberStyleFormatter());
		}
		else if (style == Style.PERCENT) {
			return new NumberDecoratingFormatter(new PercentStyleFormatter());
		}
		else {
			return new NumberDecoratingFormatter(new CurrencyStyleFormatter());
		}
	}
}
 
Example 8
public static void main(String[] args) {

	MonetaryAmount money = Money.of(BigDecimal.valueOf(100D), DOLLAR);
	MonetaryAmount min = Money.of(BigDecimal.valueOf(6D), DOLLAR);
	MonetaryAmount max = Money.of(BigDecimal.valueOf(100D), DOLLAR);
	
	List<MonetaryAmount> moneys = getMoneys();
	
	List<MonetaryAmount> justDollar = moneys.stream()
			.filter((MonetaryFunctions.isCurrency(DOLLAR)))
			.collect(Collectors.toList());
	List<MonetaryAmount> notEuro = moneys.stream().filter((MonetaryFunctions.isCurrency(EURO))).collect(Collectors.toList());
	List<MonetaryAmount> dollarGreaterOneHundred = moneys.stream().filter((MonetaryFunctions.isCurrency(DOLLAR).and(MonetaryFunctions.isGreaterThan(money)))).collect(Collectors.toList());
	List<MonetaryAmount> dollarGreaterOneHundredDistinct = moneys.stream().distinct().filter((MonetaryFunctions.isCurrency(DOLLAR).and(MonetaryFunctions.isGreaterThan(money)))).collect(Collectors.toList());
	List<MonetaryAmount> between = moneys.stream().filter((MonetaryFunctions.isCurrency(DOLLAR).and(MonetaryFunctions.isBetween(min, max)))).collect(Collectors.toList());
	
	System.out.println(justDollar);
	System.out.println(notEuro);
	System.out.println(dollarGreaterOneHundred);
	System.out.println(dollarGreaterOneHundredDistinct);
	System.out.println(between);
}
 
Example 9
@ParameterizedTest
@MethodSource("data")
void shouldUpdateExistingValueUsingTreeTraversingParser(final Class<M> type,
        final Configurer configurer) throws IOException {
    final ObjectMapper unit = unit(configurer);

    final String content = "{\"amount\":29.95,\"currency\":\"EUR\"}";
    final MonetaryAmount amount = unit.readValue(content, type);

    assertThat(amount, is(notNullValue()));

    // we need a json node to get a TreeTraversingParser with codec of type ObjectReader
    final JsonNode ownerNode =
            unit.readTree("{\"value\":{\"amount\":29.95,\"currency\":\"EUR\",\"formatted\":\"30.00EUR\"}}");

    final Owner owner = new Owner();
    owner.setValue(amount);

    // try to update
    final Owner result = unit.readerForUpdating(owner).readValue(ownerNode);
    assertThat(result, is(notNullValue()));
    assertThat(result.getValue(), is(amount));
}
 
Example 10
Source Project: jsr354-ri   Source File: MonetaryOperatorsTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test method for
 * {@link org.javamoney.moneta.function.MonetaryOperators#percent(java.lang.Number)}
 * .
 */
@Test
public void testPercentNumber() {
	MonetaryAmount m = Monetary.getDefaultAmountFactory()
			.setCurrency(
					"CHF").setNumber(100).create();
	MonetaryAmount r = m.with(MonetaryOperators.percent((long) 25));
	assertEquals(
			Monetary.getDefaultAmountFactory().setCurrency("CHF")
					.setNumber(
							new BigDecimal("25")).create(),
			r);
}
 
Example 11
Source Project: jsr354-ri   Source File: ECBCurrentRateProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConvertsDollarToBrazilian() {
    CurrencyConversion currencyConversion = provider
            .getCurrencyConversion(BRAZILIAN_REAL);
    assertNotNull(currencyConversion);
    MonetaryAmount money = Money.of(BigDecimal.TEN, DOLLAR);
    MonetaryAmount result = currencyConversion.apply(money);

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

}
 
Example 12
@ParameterizedTest
@MethodSource("data")
void shouldDeserializeCorrectlyWhenPropertiesAreInDifferentOrder(final Class<M> type,
        final Configurer configurer) throws IOException {
    final ObjectMapper unit = unit(configurer);

    final String content = "{\"currency\":\"EUR\",\"amount\":29.95}";
    final MonetaryAmount amount = unit.readValue(content, type);

    assertThat(amount.getNumber().numberValueExact(BigDecimal.class), is(new BigDecimal("29.95")));
    assertThat(amount.getCurrency().getCurrencyCode(), is("EUR"));
}
 
Example 13
Source Project: javamoney-examples   Source File: MonetaryFormatTable.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void print(Appendable appendable, MonetaryAmount amount) throws IOException {
	NumberFormat format = NumberFormat.getInstance();
	format.setMaximumFractionDigits(2);
	format.setMinimumFractionDigits(2);
	appendable.append(amount.getCurrency().toString());
	appendable.append(" ").append(format.format(amount.getNumber()));
}
 
Example 14
Source Project: javamoney-lib   Source File: YahooRateProviderTest.java    License: 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 15
@Test
public void shouldReturnNegativeValueUsingRoundingTypeAndScale() {
	operator = new RoundingMonetaryAmountOperator(RoundingMode.HALF_EVEN, 4);
	CurrencyUnit currency = Monetary.getCurrency("BHD");
	MonetaryAmount money = Money.parse("BHD -1.34534432");
	MonetaryAmount result = operator.apply(money);
	assertEquals(result.getCurrency(), currency);
	assertEquals(result.getNumber().doubleValue(), -1.3453);
}
 
Example 16
Source Project: jsr354-ri   Source File: MonetaryFunctionsFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void isGreaterThanOrEqualToTest() {
	MonetaryAmount money = FastMoney.of(1, BRAZILIAN_REAL);
	List<MonetaryAmount> justRealList = currencies().filter(isCurrency(BRAZILIAN_REAL).and(isGreaterThanOrEqualTo(money))).collect(
			Collectors.toList());
	Assert.assertEquals(2, justRealList.size());
}
 
Example 17
Source Project: jsr354-ri   Source File: StreamFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static Stream<MonetaryAmount> currenciesToSummary() {
    Money r1 = Money.of(BigDecimal.TEN, BRAZILIAN_REAL);
    Money r2 = Money.of(BigDecimal.ZERO, BRAZILIAN_REAL);
    Money r3 = Money.of(BigDecimal.ONE, BRAZILIAN_REAL);
    Money r4 = Money.of(BigDecimal.ONE, BRAZILIAN_REAL);
    Money r5 = Money.of(BigDecimal.ONE, BRAZILIAN_REAL);
    Money r6 = Money.of(BigDecimal.ONE, BRAZILIAN_REAL);
    Money r7 = Money.of(BigDecimal.ONE, BRAZILIAN_REAL);
    Money r8 = Money.of(BigDecimal.ONE, BRAZILIAN_REAL);

    Money e1 = Money.of(BigDecimal.TEN, EURO);
    Money d1 = Money.of(BigDecimal.ONE, DOLLAR);
    return Stream.of(r1, r2, r3, r4, r5, r6, r7, r8, e1, d1);
}
 
Example 18
Source Project: jsr354-ri   Source File: IMFRateProviderTest.java    License: 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 19
Source Project: jsr354-ri   Source File: ECBCurrentRateProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnsSameDollarValue() {
    CurrencyConversion currencyConversion = provider.getCurrencyConversion(DOLLAR);
    assertNotNull(currencyConversion);
    MonetaryAmount money = Money.of(BigDecimal.TEN, DOLLAR);
    MonetaryAmount result = currencyConversion.apply(money);

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

}
 
Example 20
@Override
public MonetaryAmount readFrom(Class<MonetaryAmount> type,
		Type genericType, Annotation[] annotations, MediaType mediaType,
		MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
		throws IOException, WebApplicationException {

	String text = IOUtils.toString(entityStream);
	return Money.parse(text);
}
 
Example 21
Source Project: jsr354-ri   Source File: ECBCurrentRateProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnsSameEuroValue() {
    CurrencyConversion currencyConversion = provider
            .getCurrencyConversion(EURO);
    assertNotNull(currencyConversion);
    MonetaryAmount money = Money.of(BigDecimal.TEN, EURO);
    MonetaryAmount result = currencyConversion.apply(money);

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

}
 
Example 22
Source Project: jsr354-ri   Source File: MonetaryFunctionsFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void isBetweenTest() {
	MonetaryAmount min = FastMoney.of(0, BRAZILIAN_REAL);
	MonetaryAmount max = FastMoney.of(10, BRAZILIAN_REAL);
	List<MonetaryAmount> justRealList = currencies().filter(isCurrency(BRAZILIAN_REAL).and(isBetween(min, max))).collect(
			Collectors.toList());
	Assert.assertEquals(3, justRealList.size());
}
 
Example 23
Source Project: jsr354-ri   Source File: FastMoneyProducerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateMonetaryAmount() {
	Long value = 10L;
	MonetaryAmount amount = producer.create(currency, value);
	assertEquals(amount.getCurrency(), currency);
	assertEquals(Long.valueOf(amount.getNumber().longValue()), value);
}
 
Example 24
Source Project: javamoney-examples   Source File: Person.java    License: Apache License 2.0 5 votes vote down vote up
Person(String nameArg, LocalDate birthdayArg, Sex genderArg,
		String emailArg, MonetaryAmount salArg) {
	name = nameArg;
	birthday = birthdayArg;
	gender = genderArg;
	emailAddress = emailArg;
	salary = salArg;
}
 
Example 25
Source Project: jsr354-ri   Source File: PermilOperatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnNegativeValue() {
	CurrencyUnit currency = Monetary.getCurrency("EUR");
	MonetaryAmount money = Money.parse("EUR -2.35");
	MonetaryAmount result = operator.apply(money);
	assertEquals(result.getCurrency(), currency);
	assertEquals(result.getNumber().doubleValue(), -0.0235);

}
 
Example 26
@Override
public String print(MonetaryAmount object, Locale locale) {
	CurrencyStyleFormatter formatter = new CurrencyStyleFormatter();
	formatter.setCurrency(Currency.getInstance(object.getCurrency().getCurrencyCode()));
	formatter.setPattern(this.pattern);
	return formatter.print(object.getNumber(), locale);
}
 
Example 27
Source Project: jsr354-ri   Source File: StreamFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static Stream<MonetaryAmount> currencies() {
    Money r1 = Money.of(BigDecimal.TEN, BRAZILIAN_REAL);
    Money r2 = Money.of(BigDecimal.ZERO, BRAZILIAN_REAL);
    Money r3 = Money.of(BigDecimal.ONE, BRAZILIAN_REAL);

    Money e1 = Money.of(BigDecimal.TEN, EURO);
    Money e2 = Money.of(BigDecimal.ZERO, EURO);
    Money e3 = Money.of(BigDecimal.ONE, EURO);

    Money d1 = Money.of(BigDecimal.TEN, DOLLAR);
    Money d2 = Money.of(BigDecimal.ZERO, DOLLAR);
    Money d3 = Money.of(BigDecimal.ONE, DOLLAR);
    return Stream.of(r1, r2, r3, e1, e2, e3, d1, d2, d3);
}
 
Example 28
Source Project: jsr354-ri   Source File: MoneyProducerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateMonetaryAmount() {
	Long value = 10L;
	MonetaryAmount amount = producer.create(currency, value);
	assertEquals(amount.getCurrency(), currency);
	assertEquals(Long.valueOf(amount.getNumber().longValue()), value);
}
 
Example 29
Source Project: jsr354-ri   Source File: FastMoneyProducer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public MonetaryAmount create(CurrencyUnit currency, Number number) {
	return FastMoney.of(Objects.requireNonNull(number), Objects.requireNonNull(currency));
}
 
Example 30
Source Project: javamoney-examples   Source File: AmericaStoreCommerce.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public MonetaryAmount expensive(List<Product> products) {
	 return ecommerce.expensive(products);
}