/** @param args */
  public static void main(String[] args) {
    Double doubleValue = Double.valueOf(123456789.555D);
    Locale locale = Locale.getDefault();
    Currency currency = Currency.getInstance(locale);
    NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);

    System.out.println("locale:" + locale.getDisplayName());
    System.out.println("Currency:" + currency.getDisplayName());
    System.out.println(numberFormat.format(doubleValue));

    System.out.println(
        "Locale.FRANCE:" + NumberFormat.getCurrencyInstance(Locale.FRANCE).format(doubleValue));
  }
示例#2
0
 private static String a(Locale locale, double d1, Currency currency, boolean flag)
 {
     String s;
     String s1;
     StringBuilder stringbuilder;
     boolean flag1;
     if (a(locale, currency) == 0)
     {
         flag1 = true;
     } else
     {
         flag1 = false;
     }
     s = currency.getSymbol();
     s1 = currency.getCurrencyCode();
     try
     {
         stringbuilder = new StringBuilder();
     }
     // Misplaced declaration of an exception variable
     catch (Locale locale)
     {
         return "";
     }
     if (flag1) goto _L2; else goto _L1
  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)) {

      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();
  }
  /** @tests java.text.DecimalFormatSymbols#setInternationalCurrencySymbol(java.lang.String) */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "setInternationalCurrencySymbol",
      args = {java.lang.String.class})
  @KnownFailure("getCurrency() doesn't return null for bogus currency code.")
  public void test_setInternationalCurrencySymbolLjava_lang_String() {
    Locale locale = Locale.CANADA;
    DecimalFormatSymbols dfs =
        ((DecimalFormat) NumberFormat.getCurrencyInstance(locale)).getDecimalFormatSymbols();
    Currency currency = Currency.getInstance("JPY");
    dfs.setInternationalCurrencySymbol(currency.getCurrencyCode());

    assertTrue("Test1: Returned incorrect currency", currency == dfs.getCurrency());
    assertEquals(
        "Test1: Returned incorrect currency symbol",
        currency.getSymbol(locale),
        dfs.getCurrencySymbol());
    assertTrue(
        "Test1: Returned incorrect international currency symbol",
        currency.getCurrencyCode().equals(dfs.getInternationalCurrencySymbol()));

    String symbol = dfs.getCurrencySymbol();
    dfs.setInternationalCurrencySymbol("bogus");
    assertNull("Test2: Returned incorrect currency", dfs.getCurrency());
    assertTrue("Test2: Returned incorrect currency symbol", dfs.getCurrencySymbol().equals(symbol));
    assertEquals(
        "Test2: Returned incorrect international currency symbol",
        "bogus",
        dfs.getInternationalCurrencySymbol());
  }
示例#5
0
 /**
  * This method tries to evaluate the localized display name for a {@link CurrencyUnit}. It uses
  * {@link Currency#getDisplayName(Locale)} if the given currency code maps to a JDK {@link
  * Currency} instance.
  *
  * <p>If not found {@code currency.getCurrencyCode()} is returned.
  *
  * @param currency The currency, not {@code null}
  * @return the formatted currency name.
  */
 private String getCurrencyName(CurrencyUnit currency) {
   Currency jdkCurrency = getCurrency(currency.getCurrencyCode());
   if (jdkCurrency != null) {
     return jdkCurrency.getDisplayName(locale);
   }
   return currency.getCurrencyCode();
 }
示例#6
0
  public void test(TestHarness harness) {
    Currency currency;
    boolean threwException;

    /* Check getInstance with a null string */
    threwException = false;
    try {
      currency = Currency.getInstance((String) null);
    } catch (NullPointerException exception) {
      threwException = true;
    }
    harness.check(threwException, "Currency instance request with null string exception check.");
    /* Check getInstance with a non-existant ISO string */
    threwException = false;
    try {
      currency = Currency.getInstance(INVALID_CURRENCY_CODE);
    } catch (IllegalArgumentException exception) {
      threwException = true;
    }
    harness.check(
        threwException,
        "Currency instance request with invalid currency code string exception check.");
    /* Check getInstance with a null locale */
    threwException = false;
    try {
      currency = Currency.getInstance((Locale) null);
    } catch (NullPointerException exception) {
      threwException = true;
    }
    harness.check(threwException, "Currency instance request with null locale exception check.");
  }
  @Nullable
  public static String getCurrencyName(String code) {
    String currencyName = null;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
      try {
        Currency currency = Currency.getInstance(code);
        currencyName = currency.getDisplayName(Locale.getDefault());
      } catch (final IllegalArgumentException x) {
        /* ignore */
      }
    } else {
      currencyName = Currencies.CURRENCY_NAMES.get(code);
    }

    // Try cryptocurrency codes
    if (currencyName == null) {
      try {
        CoinType cryptoCurrency = CoinID.typeFromSymbol(code);
        currencyName = cryptoCurrency.getName();
      } catch (final IllegalArgumentException x) {
        /* ignore */
      }
    }

    return currencyName;
  }
示例#8
0
 /**
  * This method tries to evaluate the localized symbol name for a {@link CurrencyUnit}. It uses
  * {@link Currency#getSymbol(Locale)} if the given currency code maps to a JDK {@link Currency}
  * instance.
  *
  * <p>If not found {@code currency.getCurrencyCode()} is returned.
  *
  * @param currency The currency, not {@code null}
  * @return the formatted currency symbol.
  */
 private String getCurrencySymbol(CurrencyUnit currency) {
   Currency jdkCurrency = getCurrency(currency.getCurrencyCode());
   if (jdkCurrency != null) {
     return jdkCurrency.getSymbol(locale);
   }
   return currency.getCurrencyCode();
 }
示例#9
0
  public void test(TestHarness harness) {
    Currency currency;

    /* Set default Locale for the JVM */
    Locale.setDefault(TEST_LOCALE);
    /* Get an instance of the currency */
    currency = Currency.getInstance(TEST_LOCALE);
    /* Check for the correct currency code */
    harness.check(
        currency.getCurrencyCode(),
        ISO4217_CODE,
        "ISO 4217 currency code retrieval check (" + currency.getCurrencyCode() + ").");
    /* Check for the correct currency symbol */
    harness.check(
        currency.getSymbol(),
        CURRENCY_SYMBOL,
        "Currency symbol retrieval check (" + currency.getSymbol() + ").");
    /* Check for the correct fraction digits */
    harness.check(
        currency.getDefaultFractionDigits(),
        FRACTION_DIGITS,
        "Currency fraction digits retrieval check (" + currency.getDefaultFractionDigits() + ").");
    /* Check for the correct currency code from toString()*/
    harness.check(
        currency.toString(),
        ISO4217_CODE,
        "ISO 4217 currency code retrieval check (" + currency.toString() + ").");
  }
示例#10
0
    /** Set the expected and actual values from their string representations */
    private void setValuesFromStrings() {
      String blurb = "";
      String origEv = getEv();
      String origAv = getAv();
      Currency curr = Currency.getInstance(Locale.getDefault());
      String currSymbol = curr.getSymbol();
      setAv(getAv().replace(currSymbol, ""));
      setEv(getEv().replace(currSymbol, ""));

      if (!getComp().equalsIgnoreCase("between")) {
        try {
          expected = BigDecimal.valueOf(Double.valueOf(getEv()));
        } catch (Exception ex) {
          blurb = "Invalid (expected) Currency value: " + Util.sq(origEv) + "  ";
        }
      }

      try {
        actual = BigDecimal.valueOf(Double.valueOf(getAv()));
      } catch (Exception ex) {
        blurb += "Invalid (actual) Currency value: " + Util.sq(origAv) + "  ";
      }

      if (!isBlank(blurb)) {
        isSpecError = true;
        addError(blurb + "Verification aborted.");
      }
    } // setValuesFromStrings
  /** @tests java.text.DecimalFormatSymbols#setCurrency(java.util.Currency) */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "setCurrency",
      args = {java.util.Currency.class})
  public void test_setCurrencyLjava_util_Currency() {
    Locale locale = Locale.CANADA;
    DecimalFormatSymbols dfs =
        ((DecimalFormat) NumberFormat.getCurrencyInstance(locale)).getDecimalFormatSymbols();

    try {
      dfs.setCurrency(null);
      fail("Expected NullPointerException");
    } catch (NullPointerException e) {
    }

    Currency currency = Currency.getInstance("JPY");
    dfs.setCurrency(currency);

    assertTrue("Returned incorrect currency", currency == dfs.getCurrency());
    assertEquals(
        "Returned incorrect currency symbol", currency.getSymbol(locale), dfs.getCurrencySymbol());
    assertTrue(
        "Returned incorrect international currency symbol",
        currency.getCurrencyCode().equals(dfs.getInternationalCurrencySymbol()));
  }
示例#12
0
  /**
   * Builds a new currency instance for this locale. All components of the given locale, other than
   * the country code, are ignored. The results of calling this method may vary over time, as the
   * currency associated with a particular country changes. For countries without a given currency
   * (e.g. Antarctica), the result is null.
   *
   * @param locale a <code>Locale</code> instance.
   * @return a new <code>Currency</code> instance.
   * @throws NullPointerException if the locale or its country code is null.
   * @throws IllegalArgumentException if the country of the given locale is not a supported ISO3166
   *     code.
   */
  public static Currency getInstance(Locale locale) {
    /**
     * The new instance must be the only available instance for the currency it supports. We ensure
     * this happens, while maintaining a suitable performance level, by creating the appropriate
     * object on the first call to this method, and returning the cached instance on later calls.
     */
    Currency newCurrency;

    String country = locale.getCountry();
    if (locale == null || country == null) {
      throw new NullPointerException("The locale or its country is null.");
    }
    /* Attempt to get the currency from the cache */
    String code = (String) countryMap.get(country);
    if (code == null) {
      /* Create the currency for this locale */
      newCurrency = new Currency(locale);
      /*
       * If the currency code is null, then creation failed
       * and we return null.
       */
      code = newCurrency.getCurrencyCode();
      if (code == null) {
        return null;
      } else {
        /* Cache it */
        countryMap.put(country, code);
        cache.put(code, newCurrency);
      }
    } else {
      newCurrency = (Currency) cache.get(code);
    }
    /* Return the instance */
    return newCurrency;
  }
  static {
    String[] ids = null;

    try {
      Set<String> set = new TreeSet<>();

      Locale[] locales = Locale.getAvailableLocales();

      for (int i = 0; i < locales.length; i++) {
        Locale locale = locales[i];

        if (locale.getCountry().length() == 2) {
          Currency currency = Currency.getInstance(locale);

          String currencyId = currency.getCurrencyCode();

          set.add(currencyId);
        }
      }

      ids = set.toArray(new String[set.size()]);
    } catch (Exception e) {
      ids = new String[] {"USD", "CAD", "EUR", "GBP", "JPY"};
    } finally {
      CURRENCY_IDS = ids;
    }
  }
示例#14
0
 public static String getIsoCodeFromAlphaCode(String alphacode) throws IllegalArgumentException {
   try {
     Currency c = findCurrency(alphacode);
     return ISOUtil.zeropad(Integer.toString(c.getIsoCode()), 3);
   } catch (ISOException e) {
     throw new IllegalArgumentException("Failed getIsoCodeFromAlphaCode/ zeropad failed?", e);
   }
 }
 /**
  * Sets the currency of these DecimalFormatSymbols. This also sets the currency symbol attribute
  * to the currency's symbol in the DecimalFormatSymbols' locale, and the international currency
  * symbol attribute to the currency's ISO 4217 currency code.
  *
  * @param currency the new currency to be used
  * @exception NullPointerException if <code>currency</code> is null
  * @since 1.4
  * @see #setCurrencySymbol
  * @see #setInternationalCurrencySymbol
  */
 public void setCurrency(Currency currency) {
   if (currency == null) {
     throw new NullPointerException();
   }
   this.currency = currency;
   intlCurrencySymbol = currency.getCurrencyCode();
   currencySymbol = currency.getSymbol(locale);
 }
示例#16
0
 public String toString(Locale locale) {
   String symbol = currency.getSymbol(locale);
   if (!"$".equals(symbol)) {
     symbol = symbol + " ";
   }
   return symbol
       + NumberFormatter.commas(amount.doubleValue(), currency.getDefaultFractionDigits());
 }
  private void initBaseCurrency(SQLiteDatabase db) {
    Cursor currencyCursor;

    // currencies
    try {
      CurrencyService currencyService = new CurrencyService(getContext());
      Currency systemCurrency = currencyService.getSystemDefaultCurrency();
      if (systemCurrency == null) return;

      InfoService infoService = new InfoService(getContext());

      currencyCursor =
          db.rawQuery(
              "SELECT * FROM "
                  + infoService.repository.getSource()
                  + " WHERE "
                  + Info.INFONAME
                  + "=?",
              new String[] {InfoKeys.BASECURRENCYID});
      if (currencyCursor == null) return;

      boolean recordExists = currencyCursor.moveToFirst();
      int recordId = currencyCursor.getInt(currencyCursor.getColumnIndex(Info.INFOID));
      currencyCursor.close();

      // Use the system default currency.
      int currencyId =
          currencyService.loadCurrencyIdFromSymbolRaw(db, systemCurrency.getCurrencyCode());

      if (!recordExists && (currencyId != Constants.NOT_SET)) {
        long newId = infoService.insertRaw(db, InfoKeys.BASECURRENCYID, currencyId);
        if (newId <= 0) {
          ExceptionHandler handler = new ExceptionHandler(getContext(), this);
          handler.showMessage("error inserting base currency on init");
        }
      } else {
        // Update the (empty) record to the default currency.
        long updatedRecords =
            infoService.updateRaw(db, recordId, InfoKeys.BASECURRENCYID, currencyId);
        if (updatedRecords <= 0) {
          ExceptionHandler handler = new ExceptionHandler(getContext(), this);
          handler.showMessage("error updating base currency on init");
        }
      }

      // Can't use provider here as the database is not ready.
      //            int currencyId =
      // currencyService.loadCurrencyIdFromSymbol(systemCurrency.getCurrencyCode());
      //            String baseCurrencyId = infoService.getInfoValue(InfoService.BASECURRENCYID);
      //            if (!StringUtils.isEmpty(baseCurrencyId)) return;
      //            infoService.setInfoValue(InfoService.BASECURRENCYID,
      // Integer.toString(currencyId));
    } catch (Exception e) {
      ExceptionHandler handler = new ExceptionHandler(getContext(), this);
      handler.handle(e, "init database, currency");
    }
  }
示例#18
0
 CurrencyConverter() {
   Arrays.asList(Locale.getAvailableLocales())
       .stream()
       .filter(locale -> StringUtils.hasText(locale.getCountry()))
       .forEach(
           locale ->
               currencies.put(
                   Currency.getInstance(locale).getCurrencyCode(),
                   Currency.getInstance(locale).getSymbol(locale)));
 }
 private void exportCommodity(XmlSerializer xmlSerializer, List<Currency> currencies)
     throws IOException {
   for (Currency currency : currencies) {
     xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY);
     xmlSerializer.attribute(null, GncXmlHelper.ATTR_KEY_VERSION, "2.0.0");
     xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
     xmlSerializer.text("ISO4217");
     xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_SPACE);
     xmlSerializer.startTag(null, GncXmlHelper.TAG_COMMODITY_ID);
     xmlSerializer.text(currency.getCurrencyCode());
     xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY_ID);
     xmlSerializer.endTag(null, GncXmlHelper.TAG_COMMODITY);
   }
 }
示例#20
0
 public static String a(double d1, Currency currency)
 {
     DecimalFormat decimalformat;
     String s;
     boolean flag;
     if (a(currency).equals(","))
     {
         decimalformat = (DecimalFormat)NumberFormat.getInstance(d);
     } else
     {
         decimalformat = (DecimalFormat)NumberFormat.getInstance(c);
     }
     s = "#######0";
     if (b.indexOf(currency.getCurrencyCode().toUpperCase(Locale.US)) == -1)
     {
         flag = true;
     } else
     {
         flag = false;
     }
     currency = s;
     if (flag)
     {
         currency = "#####0.00";
     }
     decimalformat.applyPattern(currency);
     return decimalformat.format(d1);
 }
示例#21
0
文件: IBTrader.java 项目: klon/jtrade
 private static boolean isCurrencyCode(String str) {
   try {
     return (Currency.getInstance(str.toUpperCase()) != null);
   } catch (IllegalArgumentException e) {
   }
   return false;
 }
  /**
   * Creates a simple store.
   *
   * @return The store created using default values.
   */
  public Store createStore() {
    String country = "Canada";
    String name = "Store 1";
    StoreType storeType = StoreType.B2B;
    String subCountry = "Canada";
    String url = "http://www.some-where-out-there.com";
    TimeZone timeZone = TimeZone.getDefault();
    String code = "store";
    String emailSenderName = "some name";
    String emailSenderAddress = "*****@*****.**";
    String storeAdminEmailAddress = "*****@*****.**";
    Catalog catalog = createCatalog();
    Locale defaultLocale = Locale.getDefault();
    Currency defaultCurrency = Currency.getInstance(Locale.CANADA);

    return createStore(
        country,
        name,
        storeType,
        subCountry,
        url,
        timeZone,
        code,
        emailSenderName,
        emailSenderAddress,
        storeAdminEmailAddress,
        catalog,
        defaultLocale,
        defaultCurrency);
  }
  private void save() {
    String title = getCalculationTitle();
    Currency currency = (Currency) currencyField.getSelectedItem();
    List<String> personNames = getPersonNames();

    DataBaseHelper dbHelper = new DataBaseHelper(this);
    CalculationDataSource dataSource = new CalculationDataSource(dbHelper);
    Calculation calculation =
        dataSource.createCalculation(title, currency.getCurrencyCode(), personNames);
    dbHelper.close();

    Intent intent = new Intent(this, ExpenseListActivity.class);
    intent.putExtra(ExpenseListActivity.PARAM_CALCULATION_ID, calculation.getId());
    startActivity(intent);
    finish();
  }
 public static String localeCurrencyCode() {
   try {
     return Currency.getInstance(Locale.getDefault()).getCurrencyCode();
   } catch (final IllegalArgumentException x) {
     return null;
   }
 }
示例#25
0
 public Currency getCurrency() {
   if (isVirtual()) {
     throw new UnsupportedOperationException(
         "Virtual MtGox currencies cannot be expressed as a Java currency.");
   }
   return Currency.getInstance(currency_code);
 }
示例#26
0
 private Currency getCurrency(String currencyCode) {
   try {
     return Currency.getInstance(currencyCode);
   } catch (Exception e) {
     return null;
   }
 }
示例#27
0
 public static Object convert(PropertyType property) {
   try {
     if (Date.class.getName().equals(property.getType())) {
       return dateFormat.parse(property.getValue());
     }
     if (Double.class.getName().equals(property.getType())) {
       return numberFormat.parse(property.getValue()).doubleValue();
     }
     if (Float.class.getName().equals(property.getType())) {
       return numberFormat.parse(property.getValue()).floatValue();
     }
     if (Integer.class.getName().equals(property.getType())) {
       return numberFormat.parse(property.getValue()).intValue();
     }
     if (Long.class.getName().equals(property.getType())) {
       return numberFormat.parse(property.getValue()).longValue();
     }
     if (Byte.class.getName().equals(property.getType())) {
       return numberFormat.parse(property.getValue()).byteValue();
     }
     if (Short.class.getName().equals(property.getType())) {
       return numberFormat.parse(property.getValue()).shortValue();
     }
     if (Boolean.class.getName().equals(property.getType())) {
       return "true".equals(property.getValue());
     }
     if (Currency.class.getName().equals(property.getType())) {
       return Currency.getInstance(property.getValue());
     }
   } catch (ParseException e) {
     e.printStackTrace();
   }
   return property.getValue();
 }
  public ESInvoiceEntry.Builder getInvoiceOtherRegionsEntryBuilder() {
    ESProductEntity product =
        (ESProductEntity)
            this.injector
                .getInstance(DAOESProduct.class)
                .create(this.product.getOtherRegionProductEntity());
    this.context = this.contexts.canaryIslands().staCruzDeTenerife().getParentContext();

    ESInvoiceEntry.Builder invoiceEntryBuilder =
        this.injector.getInstance(ESInvoiceEntry.Builder.class);
    ESShippingPoint.Builder originBuilder = this.shippingPoint.getShippingPointBuilder();

    invoiceEntryBuilder.clear();

    invoiceEntryBuilder
        .setUnitAmount(AmountType.WITHOUT_TAX, ESInvoiceEntryTestUtil.AMOUNT)
        .setTaxPointDate(new Date())
        .setDescription(product.getDescription())
        .setQuantity(ESInvoiceEntryTestUtil.QUANTITY)
        .setUnitOfMeasure(product.getUnitOfMeasure())
        .setProductUID(product.getUID())
        .setContextUID(this.context.getUID())
        .setShippingOrigin(originBuilder)
        .setCurrency(Currency.getInstance("EUR"));

    return invoiceEntryBuilder;
  }
示例#29
0
  @UnityCallable
  public static void LogAppEvent(String params_str) {
    Log.v(TAG, "LogAppEvent(" + params_str + ")");
    UnityParams unity_params = UnityParams.parse(params_str);

    Bundle parameters = new Bundle();
    if (unity_params.has("parameters")) {
      UnityParams unity_params_parameter = unity_params.getParamsObject("parameters");
      parameters = unity_params_parameter.getStringParams();
    }

    if (unity_params.has("logPurchase")) {
      FB.getAppEventsLogger()
          .logPurchase(
              new BigDecimal(unity_params.getDouble("logPurchase")),
              Currency.getInstance(unity_params.getString("currency")),
              parameters);
    } else if (unity_params.hasString("logEvent")) {
      if (unity_params.has("valueToSum")) {
        FB.getAppEventsLogger()
            .logEvent(
                unity_params.getString("logEvent"),
                unity_params.getDouble("valueToSum"),
                parameters);
      } else {
        FB.getAppEventsLogger().logEvent(unity_params.getString("logEvent"), parameters);
      }
    } else {
      Log.e(TAG, "couldn't logPurchase or logEvent params: " + params_str);
    }
  }
示例#30
0
 /**
  * The constructor does not complex computations and requires simple, inputs consistent with the
  * class invariant. Other creation methods are available for convenience.
  */
 public Money(BigDecimal amount, Currency currency) {
   if (amount.scale() != currency.getDefaultFractionDigits()) {
     throw new IllegalArgumentException("Scale of amount does not match currency");
   }
   this.currency = currency;
   this.amount = amount;
 }