Java Code Examples for java.util.Currency
The following examples show how to use
java.util.Currency.
These examples are extracted from open source projects.
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 Project: j2objc Author: google File: NumberFormatTest.java License: Apache License 2.0 | 7 votes |
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 Project: stategen Author: stategen File: CurrencyHandlerCallback.java License: GNU Affero General Public License v3.0 | 6 votes |
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 #3
Source Project: google-maps-services-java Author: googlemaps File: FareAdapter.java License: Apache License 2.0 | 6 votes |
/** * 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 #4
Source Project: development Author: servicecatalog File: BillingDataRetrievalServiceBeanCurrencyIT.java License: Apache License 2.0 | 6 votes |
/** * 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 #5
Source Project: jdk8u60 Author: chenghanpeng File: CurrencyTest.java License: GNU General Public License v2.0 | 6 votes |
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 Project: sofa-acts Author: sofastack File: BaseDataUtil.java License: Apache License 2.0 | 6 votes |
@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 #7
Source Project: java-technology-stack Author: codeEngraver File: Jsr354NumberFormatAnnotationFormatterFactory.java License: MIT License | 6 votes |
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 #8
Source Project: j2objc Author: google File: NumberFormat.java License: Apache License 2.0 | 6 votes |
/** * 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 #9
Source Project: OpenEstate-IO Author: OpenEstate File: PriceType.java License: Apache License 2.0 | 6 votes |
@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 Project: development Author: servicecatalog File: CurrencyValidator.java License: Apache License 2.0 | 6 votes |
/** * 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 #11
Source Project: TencentKona-8 Author: Tencent File: NumberFormatProviderImpl.java License: GNU General Public License v2.0 | 6 votes |
/** * 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 #12
Source Project: smartcoins-wallet Author: kenCode-de File: Helper.java License: MIT License | 6 votes |
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 #13
Source Project: openjdk-jdk8u-backup Author: AdoptOpenJDK File: CurrencyTest.java License: GNU General Public License v2.0 | 6 votes |
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 Project: lucene-solr Author: apache File: CurrencyFieldType.java License: Apache License 2.0 | 5 votes |
/** * 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 #15
Source Project: spring-boot-ddd Author: sandokandias File: Money.java License: GNU General Public License v3.0 | 5 votes |
@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 #16
Source Project: lams Author: lamsfoundation File: CurrencyTypeDescriptor.java License: GNU General Public License v2.0 | 5 votes |
@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 #17
Source Project: jdk8u-dev-jdk Author: frohoff File: CurrencyTest.java License: GNU General Public License v2.0 | 5 votes |
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 #18
Source Project: fingen Author: YoshiOne File: FragmentCabbageEdit.java License: Apache License 2.0 | 5 votes |
@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()); } }); }
Example #19
Source Project: MtgDesktopCompanion Author: nicho92 File: CurrencyConverter.java License: GNU General Public License v3.0 | 5 votes |
public Double convertTo(Currency from, Double value) { if(value==null) return 0.0; return convert(from.getCurrencyCode(),getCurrentCurrency().getCurrencyCode(), value); }
Example #20
Source Project: mycollab Author: MyCollab File: CurrencyViewField.java License: GNU Affero General Public License v3.0 | 5 votes |
@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 #21
Source Project: lucene-solr Author: apache File: CurrencyValue.java License: Apache License 2.0 | 5 votes |
/** * 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); }
Example #22
Source Project: development Author: servicecatalog File: ServiceProvisioningServiceBean2IT.java License: Apache License 2.0 | 5 votes |
@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)); }
Example #23
Source Project: template-compiler Author: Squarespace File: LegacyMoneyFormatter.java License: Apache License 2.0 | 5 votes |
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 #24
Source Project: native-obfuscator Author: radioegor146 File: Bug4512215.java License: GNU General Public License v3.0 | 5 votes |
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 #25
Source Project: jsr354-ri Author: JavaMoney File: CurrenciesTest.java License: Apache License 2.0 | 5 votes |
/** * 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 #26
Source Project: jdk8u60 Author: chenghanpeng File: CurrencyTest.java License: GNU General Public License v2.0 | 5 votes |
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 #27
Source Project: conf4j Author: SabreOSS File: CurrencyConverterTest.java License: MIT License | 5 votes |
@Test public void shouldReturnNullWhenFromStringAndValueIsNull() { // when Currency converted = converter.fromString(Currency.class, null, emptyMap()); // then assertThat(converted).isNull(); }
Example #28
Source Project: OpenEstate-IO Author: OpenEstate File: AdditionalCostsType.java License: Apache License 2.0 | 5 votes |
@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 #29
Source Project: cacheonix-core Author: cacheonix File: CompositeUserTypeTest.java License: GNU Lesser General Public License v2.1 | 5 votes |
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 #30
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: CurrencyTest.java License: GNU General Public License v2.0 | 5 votes |
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); } }