下面列出了java.util.Currency#getInstance ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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");
}
}
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");
}
}
/**
* 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);
}
}
}
}
/**
* 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();
}
/**
* 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);
}
}
}
}
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č ");
}
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;
}
/**
* 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;
}
/**
* 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());
}
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();
}
@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);
}
/**
* 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());
}
/**
* 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) {
}
}
}
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");
}
}
public void test_getDisplayName_null() {
Currency currency = Currency.getInstance("CHF");
try {
currency.getDisplayName(null);
fail();
} catch (NullPointerException expected) {
}
}
/**
* Performs a currency conversion & 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);
}
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());
}
}
/**
* 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) {
}
}
}
/**
* Read.
*
* @param value the value
* @return the currency
*/
public static Currency read(String value) {
if (value==null) return null;
return Currency.getInstance(value);
}
/**
* 构造器。
*
* <p>
* 创建一个具有金额<code>amount</code>元和缺省币种的货币对象。
*
* @param amount 金额,以元为单位。
*/
public Money(String amount) {
this(amount, Currency.getInstance(DEFAULT_CURRENCY_CODE));
}