Java Code Examples for java.util.Currency#getInstance()

The following examples show how to use java.util.Currency#getInstance() . 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: NumberFormatProviderImpl.java    From hottub 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 2
Source File: CurrencyValue.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
   * Returns a string representing the currency value such as "3.14,USD" for
   * a CurrencyValue of $3.14 USD.
   */
  public String strValue() {
    int digits = 0;
    try {
      Currency currency =
        Currency.getInstance(this.getCurrencyCode());
      if (currency == null) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
            "Invalid currency code " + this.getCurrencyCode());
  }
      digits = currency.getDefaultFractionDigits();
}
    catch(IllegalArgumentException exception) {
      throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
          "Invalid currency code " + this.getCurrencyCode());
    }

    String amount = Long.toString(this.getAmount());
    if (this.getAmount() == 0) {
      amount += "000000".substring(0,digits);
    }
    return
      amount.substring(0, amount.length() - digits)
      + "." + amount.substring(amount.length() - digits)
      + "," +  this.getCurrencyCode();
  }
 
Example 3
Source File: NumberFormatProviderImpl.java    From jdk8u-jdk 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 4
Source File: CurrencyTest.java    From hottub 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: CurrencyTest.java    From openjdk-jdk9 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 6
Source File: Bug4512215.java    From jdk8u-jdk with GNU General Public License v2.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 7
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#getCurrencies(java.util.Locale, String...)}.
   */
  @Test
  public void testGetCurrencyLocale() {
      Set<CurrencyUnit> cur = Monetary.getCurrencies(Locale.US);
      assertNotNull(cur);
assertEquals(cur.size(), 1);
      Currency jdkCurrency = Currency.getInstance(Locale.US);
      CurrencyUnit unit = cur.iterator().next();
      assertEquals(jdkCurrency.getCurrencyCode(), unit.getCurrencyCode());
      assertEquals(jdkCurrency.getNumericCode(), unit.getNumericCode());
      assertEquals(jdkCurrency.getDefaultFractionDigits(),
                   unit.getDefaultFractionDigits());
  }
 
Example 8
Source File: CardShake.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
public void init(double price, double lastDayPrice,double lastWeekPrice) {
	this.price=price;
	priceDayChange = price-lastDayPrice;
	percentDayChange = ((price-lastDayPrice)/lastDayPrice)*100;
	
	priceWeekChange = price-lastWeekPrice;
	percentWeekChange = ((price-lastWeekPrice)/lastWeekPrice)*100;
	
	currency=Currency.getInstance("USD");
	
	dateUpdate=new Date();
}
 
Example 9
Source File: TestRuntime81GHILMNOP.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the bean P.
 *
 * @return the bean 81 P
 */
private Bean81P createBeanP() {
	Bean81P result=new Bean81P();
	
	result.id=24;
	result.valueCurrency =Currency.getInstance(Locale.CANADA);
	result.valueLocale =Locale.CHINA;
	return result;
}
 
Example 10
Source File: SqlLiteConnector.java    From TAcharting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public synchronized List<SQLKey> getKeyList(GeneralTimePeriod table) throws SQLException{
    getConnection();
    String procedure = String.format("SELECT DISTINCT Symbol, Currency FROM %s", table);
    Statement stmt = con.createStatement();
    ResultSet res = stmt.executeQuery(procedure);
    ArrayList<SQLKey> keys = new ArrayList<>();
    while(res.next()){
        String symbol = res.getString("Symbol").replaceAll("\\s","");
        Currency currency = Currency.getInstance(res.getString("Currency"));
        keys.add(new SQLKey(symbol,table,currency));
    }
    return keys;
}
 
Example 11
Source File: FormatUtil.java    From sms-ticket with Apache License 2.0 5 votes vote down vote up
public static String formatCurrency(double amount, String currencyCode) {
    // I don't know why this is happening but sometimes currencyCode is Kč instead of CZK
    currencyCode = currencyCode.replace("Kč", "CZK");
    Currency currency = Currency.getInstance(currencyCode);
    String formatted = LocaleUtils.formatCurrency(amount, currency);
    //hack for Czech crowns - there is no better solution because Android doesn't allow different settings for
    // locale and language
    return formatted.replace("CZK", "CZK ").replace("Kč", "Kč ");
}
 
Example 12
Source File: ValueTypeTest.java    From SODS with Apache License 2.0 5 votes vote down vote up
@Test
public void testCurrency()
{
    OfficeCurrency canada = new OfficeCurrency(Currency.getInstance(Locale.CANADA), 30.0);
    OfficeCurrency eur = new OfficeCurrency(Currency.getInstance("EUR"), 2.0);

    Sheet sheet = new Sheet("A", 1, 2);
    sheet.getDataRange().setValues(canada, eur);
    sheet = saveAndLoad(sheet);

    assertEquals(sheet.getRange(0, 0).getValue(), canada);
    assertEquals(sheet.getRange(0, 1).getValue(), eur);
}
 
Example 13
Source File: CurrencyTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.util.Currency#getDefaultFractionDigits()
 */
public void test_getDefaultFractionDigits() {

    Currency c1 = Currency.getInstance("TND");
    c1.getDefaultFractionDigits();
    assertEquals(" Currency.getInstance(\"" + c1
            + "\") returned incorrect number of digits. ", 3, c1
            .getDefaultFractionDigits());

    Currency c2 = Currency.getInstance("EUR");
    c2.getDefaultFractionDigits();
    assertEquals(" Currency.getInstance(\"" + c2
            + "\") returned incorrect number of digits. ", 2, c2
            .getDefaultFractionDigits());

    Currency c3 = Currency.getInstance("JPY");
    c3.getDefaultFractionDigits();
    assertEquals(" Currency.getInstance(\"" + c3
            + "\") returned incorrect number of digits. ", 0, c3
            .getDefaultFractionDigits());

    Currency c4 = Currency.getInstance("XXX");
    c4.getDefaultFractionDigits();
    assertEquals(" Currency.getInstance(\"" + c4
            + "\") returned incorrect number of digits. ", -1, c4
            .getDefaultFractionDigits());
}
 
Example 14
Source File: DecimalFormatSymbols.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Reads the default serializable fields, provides default values for objects
 * in older serial versions, and initializes non-serializable fields.
 * If <code>serialVersionOnStream</code>
 * is less than 1, initializes <code>monetarySeparator</code> to be
 * the same as <code>decimalSeparator</code> and <code>exponential</code>
 * to be 'E'.
 * If <code>serialVersionOnStream</code> is less than 2,
 * initializes <code>locale</code>to the root locale, and initializes
 * If <code>serialVersionOnStream</code> is less than 3, it initializes
 * <code>exponentialSeparator</code> using <code>exponential</code>.
 * Sets <code>serialVersionOnStream</code> back to the maximum allowed value so that
 * default serialization will work properly if this object is streamed out again.
 * Initializes the currency from the intlCurrencySymbol field.
 *
 * @since JDK 1.1.6
 */
private void readObject(ObjectInputStream stream)
        throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    if (serialVersionOnStream < 1) {
        // Didn't have monetarySeparator or exponential field;
        // use defaults.
        monetarySeparator = decimalSeparator;
        exponential       = 'E';
    }
    if (serialVersionOnStream < 2) {
        // didn't have locale; use root locale
        locale = Locale.ROOT;
    }
    if (serialVersionOnStream < 3) {
        // didn't have exponentialSeparator. Create one using exponential
        exponentialSeparator = Character.toString(exponential);
    }
    serialVersionOnStream = currentSerialVersion;

    if (intlCurrencySymbol != null) {
        try {
             currency = Currency.getInstance(intlCurrencySymbol);
        } catch (IllegalArgumentException e) {
        }
    }
}
 
Example 15
Source File: CurrencyTest.java    From openjdk-jdk8u-backup 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 16
Source File: CurrencyTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_getDisplayName_null() {
    Currency currency = Currency.getInstance("CHF");
    try {
        currency.getDisplayName(null);
        fail();
    } catch (NullPointerException expected) {
    }
}
 
Example 17
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 18
Source File: DecimalFormatSymbols.java    From dragonwell8_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Sets the ISO 4217 currency code of the currency of these
 * DecimalFormatSymbols.
 * If the currency code is valid (as defined by
 * {@link java.util.Currency#getInstance(java.lang.String) Currency.getInstance}),
 * this also sets the currency attribute to the corresponding Currency
 * instance and the currency symbol attribute to the currency's symbol
 * in the DecimalFormatSymbols' locale. If the currency code is not valid,
 * then the currency attribute is set to null and the currency symbol
 * attribute is not modified.
 *
 * @param currencyCode the currency code
 * @see #setCurrency
 * @see #setCurrencySymbol
 * @since 1.2
 */
public void setInternationalCurrencySymbol(String currencyCode)
{
    intlCurrencySymbol = currencyCode;
    currency = null;
    if (currencyCode != null) {
        try {
            currency = Currency.getInstance(currencyCode);
            currencySymbol = currency.getSymbol();
        } catch (IllegalArgumentException e) {
        }
    }
}
 
Example 19
Source File: Money.java    From common-utils with GNU General Public License v2.0 2 votes vote down vote up
/**
 * 构造器。
 * 
 * <p>
 * 创建一个具有金额<code>amount</code>元和缺省币种的货币对象。
 * 
 * @param amount 金额,以元为单位。
 */
public Money(String amount) {
    this(amount, Currency.getInstance(DEFAULT_CURRENCY_CODE));
}
 
Example 20
Source File: CurrencyUtils.java    From kripton with Apache License 2.0 2 votes vote down vote up
/**
 * Read.
 *
 * @param value the value
 * @return the currency
 */
public static Currency read(String value) {
	if (value==null) return null;
	return Currency.getInstance(value);
}