下面列出了怎么用java.util.Currency的API类实例代码及写法,或者点击链接到github查看源代码。
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));
}
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;
}
/**
* 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;
}
/**
* 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;
}
});
}
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");
}
}
@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);
}
}
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);
}
}
/**
* 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);
}
}
}
}
@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;
}
/**
* 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));
}
}
/**
* 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 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;
}
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");
}
}
/**
* 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;
}
@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);
}
@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() );
}
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");
}
}
@OnClick(R.id.button_system_currencies)
void selectSystemCurrencyClick() {
CabbageManager.getInstance().showSelectSystemCurrencyDialog(getActivity(), new CabbageManager.OnSelectCurrencyListener() {
@Override
public void OnSelectCurrency(Currency selectedCurrency) {
editTextName.setText(selectedCurrency.getDisplayName());
editTextCode.setText(selectedCurrency.getCurrencyCode());
editTextSymbol.setText(selectedCurrency.getSymbol());
}
});
}
public Double convertTo(Currency from, Double value)
{
if(value==null)
return 0.0;
return convert(from.getCurrencyCode(),getCurrentCurrency().getCurrencyCode(), value);
}
@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()));
}
}
/**
* 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);
}
@Test
public void testSet3CompatibleProducts_2compatible1FreeOfCharge()
throws Exception {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
SupportedCurrency sc = new SupportedCurrency();
sc.setCurrency(Currency.getInstance("USD"));
mgr.persist(sc);
return null;
}
});
VOTechnicalService techProduct = createTechnicalProduct(svcProv);
container.login(supplierUserKey, ROLE_SERVICE_MANAGER,
ROLE_TECHNOLOGY_MANAGER);
VOServiceDetails product1 = createProduct(techProduct, "product1",
svcProv);
publishToLocalMarketplaceSupplier(product1, mpSupplier);
VOServiceDetails product2 = createProduct(techProduct, "product2",
svcProv);
publishToLocalMarketplaceSupplier(product2, mpSupplier);
VOServiceDetails product3 = createProduct(techProduct, "product3",
svcProv);
publishToLocalMarketplaceSupplier(product3, mpSupplier);
VOPriceModel priceModel1 = createChargeablePriceModel();
priceModel1.setCurrencyISOCode(USD);
priceModel1.setType(PriceModelType.FREE_OF_CHARGE);
VOPriceModel priceModel2 = createChargeablePriceModel();
priceModel2.setCurrencyISOCode(USD);
VOPriceModel priceModel3 = createChargeablePriceModel();
product1 = svcProv.savePriceModel(product1, priceModel1);
product2 = svcProv.savePriceModel(product2, priceModel2);
product3 = svcProv.savePriceModel(product3, priceModel3);
svcProv.setCompatibleServices(product1,
Arrays.asList((VOService) product2, product3));
}
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);
}
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());
}
}
/**
* 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());
}
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);
}
}
@Test
public void shouldReturnNullWhenFromStringAndValueIsNull() {
// when
Currency converted = converter.fromString(Currency.class, null, emptyMap());
// then
assertThat(converted).isNull();
}
@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;
}
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();
}
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);
}
}