javax.money.MonetaryAmount Java Examples

The following examples show how to use javax.money.MonetaryAmount. 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: MonetarySorterOperations.java    From javamoney-examples with Apache License 2.0 7 votes vote down vote up
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 File: JavaMoneyUnitManualTest.java    From tutorials with 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 #3
Source File: Totalable.java    From salespoint with 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 #4
Source File: MoneyModule.java    From jackson-datatype-money with 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 #5
Source File: MonetaryAmountDeserializerTest.java    From jackson-datatype-money with MIT License 6 votes vote down vote up
@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 #6
Source File: Jsr354NumberFormatAnnotationFormatterFactory.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: MonetaryFilterOperations.java    From javamoney-examples with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: ConversionExample.java    From javamoney-examples with 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 #9
Source File: ECBHistoric90RateProviderTest.java    From jsr354-ri with 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 #10
Source File: PermilOperatorTest.java    From jsr354-ri with 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 #11
Source File: ECBCurrentRateProviderTest.java    From jsr354-ri with 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 #12
Source File: YahooRateProviderTest.java    From javamoney-lib 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 #13
Source File: ECBCurrentRateProviderTest.java    From jsr354-ri with 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 #14
Source File: MoneyProducerTest.java    From jsr354-ri with 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 #15
Source File: Jsr354NumberFormatAnnotationFormatterFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #16
Source File: MonetaryOperatorsTest.java    From jsr354-ri with 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 #17
Source File: MonetaryAmountDeserializerTest.java    From jackson-datatype-money with MIT License 5 votes vote down vote up
@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 #18
Source File: StreamFactory.java    From jsr354-ri with 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 #19
Source File: MonetaryFormatTable.java    From javamoney-examples with 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 #20
Source File: Person.java    From javamoney-examples with 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 #21
Source File: RoundingMonetaryAmountOperatorTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: FastMoneyProducerTest.java    From jsr354-ri with 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 #23
Source File: MonetaryFunctionsFilterTest.java    From jsr354-ri with 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 #24
Source File: MonetaryFunctionsFilterTest.java    From jsr354-ri with 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 #25
Source File: ECBCurrentRateProviderTest.java    From jsr354-ri with 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 #26
Source File: MonetaryAmountReaderProvider.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
@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 #27
Source File: StreamFactory.java    From jsr354-ri with 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 #28
Source File: IMFRateProviderTest.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 #29
Source File: RoundedMoneyProducer.java    From jsr354-ri with Apache License 2.0 4 votes vote down vote up
@Override
public MonetaryAmount create(CurrencyUnit currency, Number number) {
	return RoundedMoney.of(Objects.requireNonNull(number), Objects.requireNonNull(currency), operator);
}
 
Example #30
Source File: MonetaryFunctionsFilterTest.java    From jsr354-ri with Apache License 2.0 4 votes vote down vote up
@Test
public void isNotCurrencyTest() {
	List<MonetaryAmount> justRealList = currencies().filter(filterByExcludingCurrency(BRAZILIAN_REAL)).collect(
			Collectors.toList());
	Assert.assertEquals(6, justRealList.size());
}