java.util.Currency Java Examples

The following examples show how to use java.util.Currency. 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: NumberFormatTest.java    From j2objc with Apache License 2.0 7 votes vote down vote up
public void test_issue79925() {
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
    nf.setCurrency(Currency.getInstance("EUR"));
    assertEquals("€50.00", nf.format(50.0));

    DecimalFormatSymbols decimalFormatSymbols = ((DecimalFormat) nf).getDecimalFormatSymbols();
    decimalFormatSymbols.setCurrencySymbol("");
    ((DecimalFormat) nf).setDecimalFormatSymbols(decimalFormatSymbols);
    assertEquals("50.00", nf.format(50.0));

    nf.setCurrency(Currency.getInstance("SGD"));
    assertEquals("SGD50.00", nf.format(50.0));

    nf.setCurrency(Currency.getInstance("SGD"));
    assertEquals("SGD50.00", nf.format(50.00));

    nf.setCurrency(Currency.getInstance("USD"));
    assertEquals("$50.00", nf.format(50.0));

    nf.setCurrency(Currency.getInstance("SGD"));
    assertEquals("SGD50.00", nf.format(50.0));
}
 
Example #2
Source File: BaseDataUtil.java    From sofa-acts with Apache License 2.0 6 votes vote down vote up
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property,
                                              Object propertyValue, Tag customTag) {
    if (property.getType().equals(Currency.class)) {

        Node node = null;
        if (StringUtils.isBlank(String.valueOf(propertyValue))
            || String.valueOf(propertyValue).equals("null")) {
            node = representScalar(Tag.STR, "null");
        } else {
            node = representScalar(Tag.STR, ((Currency) propertyValue).getCurrencyCode());
        }
        return new NodeTuple(representScalar(Tag.STR, property.getName()), node);
    } else if (property.getType().equals(StackTraceElement[].class)) {
        //Return null to skip theproperty
        return null;
    } else {
        super.getPropertyUtils().setSkipMissingProperties(true);
        return super
            .representJavaBeanProperty(javaBean, property, propertyValue, customTag);
    }
}
 
Example #3
Source File: CurrencyHandlerCallback.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
public Object getResult(ResultGetter getter) throws SQLException {
        Object result = null;
        
//        if (getter.wasNull()){
//            return null;
//        }
        
        Object value =getter.getObject();
        if (value!=null) {
            String currStr =getter.getString();
            if (StringUtil.isNotBlank(currStr)){
                Currency currency =getCurrency(currStr);
                return currency;
            }
        }
        return result;
    }
 
Example #4
Source File: CurrencyTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
static void testSerialization() throws Exception {
    Currency currency1 = Currency.getInstance("DEM");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oStream = new ObjectOutputStream(baos);
    oStream.writeObject(currency1);
    oStream.flush();
    byte[] bytes = baos.toByteArray();

    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    ObjectInputStream iStream = new ObjectInputStream(bais);
    Currency currency2 = (Currency) iStream.readObject();

    if (currency1 != currency2) {
        throw new RuntimeException("serialization breaks class invariant");
    }
}
 
Example #5
Source File: Helper.java    From smartcoins-wallet with MIT License 6 votes vote down vote up
public static NumberFormat newCurrencyFormat(Context context, Currency currency, Locale displayLocale) {
        Log.d(TAG, "newCurrencyFormat");
        NumberFormat retVal = NumberFormat.getCurrencyInstance(displayLocale);
        retVal.setCurrency(currency);

        //The default JDK handles situations well when the currency is the default currency for the locale
//        if (currency.equals(Currency.getInstance(displayLocale))) {
//            Log.d(TAG, "Let the JDK handle this");
//            return retVal;
//        }

        //otherwise we need to "fix things up" when displaying a non-native currency
        if (retVal instanceof DecimalFormat) {
            DecimalFormat decimalFormat = (DecimalFormat) retVal;
            String correctedI18NSymbol = getCorrectedInternationalCurrencySymbol(context, currency, displayLocale);
            if (correctedI18NSymbol != null) {
                DecimalFormatSymbols dfs = decimalFormat.getDecimalFormatSymbols(); //this returns a clone of DFS
                dfs.setInternationalCurrencySymbol(correctedI18NSymbol);
                dfs.setCurrencySymbol(correctedI18NSymbol);
                decimalFormat.setDecimalFormatSymbols(dfs);
            }
        }

        return retVal;
    }
 
Example #6
Source File: NumberFormatProviderImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adjusts the minimum and maximum fraction digits to values that
 * are reasonable for the currency's default fraction digits.
 */
private static void adjustForCurrencyDefaultFractionDigits(
        DecimalFormat format, DecimalFormatSymbols symbols) {
    Currency currency = symbols.getCurrency();
    if (currency == null) {
        try {
            currency = Currency.getInstance(symbols.getInternationalCurrencySymbol());
        } catch (IllegalArgumentException e) {
        }
    }
    if (currency != null) {
        int digits = currency.getDefaultFractionDigits();
        if (digits != -1) {
            int oldMinDigits = format.getMinimumFractionDigits();
            // Common patterns are "#.##", "#.00", "#".
            // Try to adjust all of them in a reasonable way.
            if (oldMinDigits == format.getMaximumFractionDigits()) {
                format.setMinimumFractionDigits(digits);
                format.setMaximumFractionDigits(digits);
            } else {
                format.setMinimumFractionDigits(Math.min(digits, oldMinDigits));
                format.setMaximumFractionDigits(digits);
            }
        }
    }
}
 
Example #7
Source File: CurrencyValidator.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Validates that the given value contains an currency ISO code.
 * 
 * @param context
 *            FacesContext for the request we are processing
 * @param component
 *            UIComponent we are checking for correctness
 * @param value
 *            the value to validate
 * @throws ValidatorException
 *             if validation fails
 */
public void validate(FacesContext facesContext, UIComponent component,
        Object value) throws ValidatorException {
    if (value == null) {
        return;
    }
    String currencyCode = value.toString();
    if (currencyCode.length() == 0) {
        return;
    }
    try {
        Currency.getInstance(currencyCode);
    } catch (IllegalArgumentException e) {
        String label = JSFUtils.getLabel(component);
        ValidationException ve = new ValidationException(
                ReasonEnum.INVALID_CURRENCY, label,
                new Object[] { currencyCode });
        String text = JSFUtils.getText(ve.getMessageKey(),
                new Object[] { currencyCode }, facesContext);
        throw new ValidatorException(new FacesMessage(
                FacesMessage.SEVERITY_ERROR, text, null));
    }
}
 
Example #8
Source File: FareAdapter.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
/**
 * Read a Fare object from the Directions API and convert to a {@link com.google.maps.model.Fare}
 *
 * <pre>{
 *   "currency": "USD",
 *   "value": 6
 * }</pre>
 */
@Override
public Fare read(JsonReader reader) throws IOException {
  if (reader.peek() == JsonToken.NULL) {
    reader.nextNull();
    return null;
  }

  Fare fare = new Fare();
  reader.beginObject();
  while (reader.hasNext()) {
    String key = reader.nextName();
    if ("currency".equals(key)) {
      fare.currency = Currency.getInstance(reader.nextString());
    } else if ("value".equals(key)) {
      // this relies on nextString() being able to coerce raw numbers to strings
      fare.value = new BigDecimal(reader.nextString());
    } else {
      // Be forgiving of unexpected values
      reader.skipValue();
    }
  }
  reader.endObject();

  return fare;
}
 
Example #9
Source File: PriceType.java    From OpenEstate-IO with Apache License 2.0 6 votes vote down vote up
@Generated(value = "com.sun.tools.xjc.Driver", date = "2018-10-12T02:55:25+02:00", comments = "JAXB RI v2.2.11")
public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy2 strategy) {
    {
        BigDecimal theValue;
        theValue = this.getValue();
        strategy.appendField(locator, this, "value", buffer, theValue, (this.value!= null));
    }
    {
        PricePeriodValue thePeriod;
        thePeriod = this.getPeriod();
        strategy.appendField(locator, this, "period", buffer, thePeriod, (this.period!= null));
    }
    {
        Currency theCurrency;
        theCurrency = this.getCurrency();
        strategy.appendField(locator, this, "currency", buffer, theCurrency, (this.currency!= null));
    }
    return buffer;
}
 
Example #10
Source File: NumberFormat.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Adjusts the minimum and maximum fraction digits to values that
 * are reasonable for the currency's default fraction digits.
 */
private static void adjustForCurrencyDefaultFractionDigits(
        DecimalFormat format, DecimalFormatSymbols symbols) {
    Currency currency = symbols.getCurrency();
    if (currency == null) {
        try {
            currency = Currency.getInstance(symbols.getInternationalCurrencySymbol());
        } catch (IllegalArgumentException e) {
        }
    }
    if (currency != null) {
        int digits = currency.getDefaultFractionDigits();
        if (digits != -1) {
            int oldMinDigits = format.getMinimumFractionDigits();
            // Common patterns are "#.##", "#.00", "#".
            // Try to adjust all of them in a reasonable way.
            if (oldMinDigits == format.getMaximumFractionDigits()) {
                format.setMinimumFractionDigits(digits);
                format.setMaximumFractionDigits(digits);
            } else {
                format.setMinimumFractionDigits(Math.min(digits, oldMinDigits));
                format.setMaximumFractionDigits(digits);
            }
        }
    }
}
 
Example #11
Source File: Jsr354NumberFormatAnnotationFormatterFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
private Currency determineCurrency(String text, Locale locale) {
	try {
		if (text.length() < 3) {
			// Could not possibly contain a currency code ->
			// try with locale and likely let it fail on parse.
			return Currency.getInstance(locale);
		}
		else if (this.pattern.startsWith(CURRENCY_CODE_PATTERN)) {
			return Currency.getInstance(text.substring(0, 3));
		}
		else if (this.pattern.endsWith(CURRENCY_CODE_PATTERN)) {
			return Currency.getInstance(text.substring(text.length() - 3));
		}
		else {
			// A pattern without a currency code...
			return Currency.getInstance(locale);
		}
	}
	catch (IllegalArgumentException ex) {
		throw new IllegalArgumentException("Cannot determine currency for number value [" + text + "]", ex);
	}
}
 
Example #12
Source File: BillingDataRetrievalServiceBeanCurrencyIT.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a subscription that is based on a price model using USD as
 * currency.
 * 
 * @param modTime
 *            The time the change to use USD should be performed at.
 * @throws Exception
 */
private void createSubUsingUSD(final long modTime) throws Exception {
    runTX(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            SupportedCurrency sc = new SupportedCurrency();
            sc.setCurrency(Currency.getInstance("USD"));
            dm.persist(sc);

            Subscription subNew = Subscriptions.createSubscription(dm,
                    Scenario.getCustomer().getOrganizationId(),
                    Scenario.getProduct().getProductId(), "SubUSD",
                    Scenario.getSupplier());
            dm.flush();
            subNew.setHistoryModificationTime(Long.valueOf(modTime));
            PriceModel priceModel = subNew.getPriceModel();
            priceModel.setCurrency(sc);
            priceModel.setHistoryModificationTime(Long.valueOf(modTime));

            return null;
        }
    });
}
 
Example #13
Source File: CurrencyTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void testSerialization() throws Exception {
    Currency currency1 = Currency.getInstance("DEM");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oStream = new ObjectOutputStream(baos);
    oStream.writeObject(currency1);
    oStream.flush();
    byte[] bytes = baos.toByteArray();

    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    ObjectInputStream iStream = new ObjectInputStream(bais);
    Currency currency2 = (Currency) iStream.readObject();

    if (currency1 != currency2) {
        throw new RuntimeException("serialization breaks class invariant");
    }
}
 
Example #14
Source File: CurrencyTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static void testValidCurrency(String currencyCode) {
    Currency currency1 = Currency.getInstance(currencyCode);
    Currency currency2 = Currency.getInstance(currencyCode);
    if (currency1 != currency2) {
        throw new RuntimeException("Didn't get same instance for same currency code");
    }
    if (!currency1.getCurrencyCode().equals(currencyCode)) {
        throw new RuntimeException("Currency code changed");
    }
}
 
Example #15
Source File: CurrencyValue.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Performs a currency conversion &amp; unit conversion.
 *
 * @param exchangeRate       Exchange rate to apply.
 * @param sourceCurrencyCode The source currency code.
 * @param sourceAmount       The source amount.
 * @param targetCurrencyCode The target currency code.
 * @return The converted indexable units after the exchange rate and currency fraction digits are applied.
 */
public static long convertAmount(double exchangeRate, String sourceCurrencyCode, long sourceAmount, String targetCurrencyCode) {
  if (targetCurrencyCode.equals(sourceCurrencyCode)) {
    return sourceAmount;
  }

  int sourceFractionDigits = Currency.getInstance(sourceCurrencyCode).getDefaultFractionDigits();
  Currency targetCurrency = Currency.getInstance(targetCurrencyCode);
  int targetFractionDigits = targetCurrency.getDefaultFractionDigits();
  return convertAmount(exchangeRate, sourceFractionDigits, sourceAmount, targetFractionDigits);
}
 
Example #16
Source File: LegacyMoneyFormatter.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
private static Currency getCurrency(JsonNode node) {
  String currencyStr = StringUtils.trimToNull(node.path(CURRENCY_FIELD_NAME).asText());
  if (currencyStr == null) {
    return DEFAULT_CURRENCY;
  }

  return Currency.getInstance(currencyStr);
}
 
Example #17
Source File: CurrencyViewField.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void doSetValue(String value) {
    if (StringUtils.isBlank(value)) {
        label.setValue("");
    } else {
        Currency currency = CurrencyUtils.getInstance(value);
        label.setValue(String.format("%s (%s)", currency.getDisplayName(UserUIContext.getUserLocale()), currency.getCurrencyCode()));
    }
}
 
Example #18
Source File: Bug4512215.java    From native-obfuscator with GNU General Public License v3.0 5 votes vote down vote up
private static void testCurrencyDefined(String currencyCode, int digits) {
    Currency currency = Currency.getInstance(currencyCode);
    if (currency.getDefaultFractionDigits() != digits) {
        throw new RuntimeException("[" + currencyCode
                + "] expected: " + digits
                + "; got: " + currency.getDefaultFractionDigits());
    }
}
 
Example #19
Source File: CurrencyTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
static void testDisplayName(String currencyCode, Locale locale, String expectedName) {
    String name = Currency.getInstance(currencyCode).getDisplayName(locale);
    if (!name.equals(expectedName)) {
        throw new RuntimeException("Wrong display name for currency " +
                currencyCode +": expected '" + expectedName +
                "', got '" + name + "'");
    }
}
 
Example #20
Source File: CurrencyTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void testInvalidCurrency(String currencyCode) {
    boolean gotException = false;
    try {
        Currency currency = Currency.getInstance(currencyCode);
    } catch (IllegalArgumentException e) {
        gotException = true;
    }
    if (!gotException) {
        throw new RuntimeException("didn't get specified exception");
    }
}
 
Example #21
Source File: CurrencyTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void testSymbol(String currencyCode, Locale locale, String expectedSymbol) {
    String symbol = Currency.getInstance(currencyCode).getSymbol(locale);
    if (!symbol.equals(expectedSymbol)) {
        throw new RuntimeException("Wrong symbol for currency " +
                currencyCode +": expected " + expectedSymbol +
                ", got " + symbol);
    }
}
 
Example #22
Source File: CurrenciesTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for
 * {@link javax.money.Monetary#getCurrency(java.lang.String, String...)} .
 */
@Test
public void testCurrencyValues() {
	Currency jdkCurrency = Currency.getInstance("CHF");
	CurrencyUnit cur = Monetary.getCurrency("CHF");
	assertNotNull(cur);
	assertEquals(jdkCurrency.getCurrencyCode(), cur.getCurrencyCode());
	assertEquals(jdkCurrency.getNumericCode(), cur.getNumericCode());
	assertEquals(jdkCurrency.getDefaultFractionDigits(),
			cur.getDefaultFractionDigits());
}
 
Example #23
Source File: CompositeUserTypeTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testCompositeUserType() {
	Session s = openSession();
	org.hibernate.Transaction t = s.beginTransaction();
	
	Transaction tran = new Transaction();
	tran.setDescription("a small transaction");
	tran.setValue( new MonetoryAmount( new BigDecimal(1.5), Currency.getInstance("USD") ) );
	s.persist(tran);
	
	List result = s.createQuery("from Transaction tran where tran.value.amount > 1.0 and tran.value.currency = 'USD'").list();
	assertEquals( result.size(), 1 );
	tran.getValue().setCurrency( Currency.getInstance("AUD") );
	result = s.createQuery("from Transaction tran where tran.value.amount > 1.0 and tran.value.currency = 'AUD'").list();
	assertEquals( result.size(), 1 );
	
	if ( !(getDialect() instanceof HSQLDialect) && ! (getDialect() instanceof Oracle9Dialect) ) {
	
		result = s.createQuery("from Transaction txn where txn.value = (1.5, 'AUD')").list();
		assertEquals( result.size(), 1 );
		result = s.createQuery("from Transaction where value = (1.5, 'AUD')").list();
		assertEquals( result.size(), 1 );
		
	}
	
	s.delete(tran);
	t.commit();
	s.close();
}
 
Example #24
Source File: CurrencyTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
static void testNumericCode(String currencyCode, int expectedNumeric) {
    int numeric = Currency.getInstance(currencyCode).getNumericCode();
    if (numeric != expectedNumeric) {
        throw new RuntimeException("Wrong numeric code for currency " +
                currencyCode +": expected " + expectedNumeric +
                ", got " + numeric);
    }
}
 
Example #25
Source File: AdditionalCostsType.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
@Generated(value = "com.sun.tools.xjc.Driver", date = "2018-10-12T02:48:12+02:00", comments = "JAXB RI v2.2.11")
public Object copyTo(ObjectLocator locator, Object target, CopyStrategy2 strategy) {
    final Object draftCopy = ((target == null)?createNewInstance():target);
    if (draftCopy instanceof AdditionalCostsType) {
        final AdditionalCostsType copy = ((AdditionalCostsType) draftCopy);
        {
            Boolean valueShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.value!= null));
            if (valueShouldBeCopiedAndSet == Boolean.TRUE) {
                BigInteger sourceValue;
                sourceValue = this.getValue();
                BigInteger copyValue = ((BigInteger) strategy.copy(LocatorUtils.property(locator, "value", sourceValue), sourceValue, (this.value!= null)));
                copy.setValue(copyValue);
            } else {
                if (valueShouldBeCopiedAndSet == Boolean.FALSE) {
                    copy.value = null;
                }
            }
        }
        {
            Boolean currencyShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, (this.currency!= null));
            if (currencyShouldBeCopiedAndSet == Boolean.TRUE) {
                Currency sourceCurrency;
                sourceCurrency = this.getCurrency();
                Currency copyCurrency = ((Currency) strategy.copy(LocatorUtils.property(locator, "currency", sourceCurrency), sourceCurrency, (this.currency!= null)));
                copy.setCurrency(copyCurrency);
            } else {
                if (currencyShouldBeCopiedAndSet == Boolean.FALSE) {
                    copy.currency = null;
                }
            }
        }
    }
    return draftCopy;
}
 
Example #26
Source File: CurrencyTypeDescriptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <X> Currency wrap(X value, WrapperOptions options) {
	if ( value == null ) {
		return null;
	}
	if ( String.class.isInstance( value ) ) {
		return Currency.getInstance( (String) value );
	}
	throw unknownWrap( value.getClass() );
}
 
Example #27
Source File: CurrencyFieldType.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * A wrapper around <code>Currency.getInstance</code> that returns null
 * instead of throwing <code>IllegalArgumentException</code>
 * if the specified Currency does not exist in this JVM.
 *
 * @see Currency#getInstance(String)
 */
public static Currency getCurrency(final String code) {
  try {
    return Currency.getInstance(code);
  } catch (IllegalArgumentException e) {
    /* :NOOP: */
  }
  return null;
}
 
Example #28
Source File: CurrencyConverterTest.java    From conf4j with MIT License 5 votes vote down vote up
@Test
public void shouldReturnNullWhenFromStringAndValueIsNull() {
    // when
    Currency converted = converter.fromString(Currency.class, null, emptyMap());

    // then
    assertThat(converted).isNull();
}
 
Example #29
Source File: Money.java    From spring-boot-ddd with GNU General Public License v3.0 5 votes vote down vote up
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public Money(@JsonProperty("currency") String currency,
             @JsonProperty("amount") Integer amount,
             @JsonProperty("scale") Integer scale) {
    this.currency = Currency.getInstance(currency).getCurrencyCode();
    this.amount = amount;
    this.scale = scale;
    this.amountAsBigDecimal = new BigDecimal(amount).movePointLeft(2).setScale(scale);
}
 
Example #30
Source File: LegacyMoneyFormatter.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(Context ctx, Arguments args, Variables variables) throws CodeExecuteException {
  Variable var = variables.first();
  JsonNode node = var.node();

  Locale locale = (Locale) args.getOpaque();
  Currency currency = getCurrency(node);
  double value = node.path(VALUE_FIELD_NAME).asDouble(0);

  String result = LegacyMoneyFormatFactory.create(locale, currency).format(value);
  var.set(result);
}