Example usage for java.text NumberFormat setCurrency

List of usage examples for java.text NumberFormat setCurrency

Introduction

In this page you can find the example usage for java.text NumberFormat setCurrency.

Prototype

public void setCurrency(Currency currency) 

Source Link

Document

Sets the currency used by this number format when formatting currency values.

Usage

From source file:org.rythmengine.utils.S.java

/**
 * Format give data into currency using locale info from the engine specified
 * //w  w  w  .j  a  v  a2s  . c o  m
 * <p>The method accept any data type. When <code>null</code> is found then 
 * <code>NullPointerException</code> will be thrown out; if an <code>Number</code>
 * is passed in, it will be type cast to <code>Number</code>; otherwise 
 * a <code>Double.valueOf(data.toString())</code> is used to find out
 * the number</p>
 *
 * @param template
 * @param data
 * @param currencyCode
 * @param locale
 * @return the currency
 */
public static String formatCurrency(ITemplate template, Object data, String currencyCode, Locale locale) {
    if (null == data)
        throw new NullPointerException();
    Number number;
    if (data instanceof Number) {
        number = (Number) data;
    } else {
        number = Double.parseDouble(data.toString());
    }
    if (null == locale)
        locale = I18N.locale(template);
    Currency currency = null == currencyCode ? Currency.getInstance(locale)
            : Currency.getInstance(currencyCode);
    NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);
    numberFormat.setCurrency(currency);
    numberFormat.setMaximumFractionDigits(currency.getDefaultFractionDigits());
    String s = numberFormat.format(number);
    s = s.replace(currency.getCurrencyCode(), currency.getSymbol(locale));
    return s;
}

From source file:biz.wolschon.fileformats.gnucash.baseclasses.SimpleAccount.java

/**
 * same as {@link #getBalance(Date)}. <br/>
 * ignores transactions after the current date+time.
 * @see #getBalance(Date)/*from w w  w.j  a va  2 s .  co  m*/
 */
public String getBalanceFormated(final Locale loc) {

    NumberFormat cf = NumberFormat.getCurrencyInstance(loc);
    cf.setCurrency(getCurrency());
    return cf.format(getBalance());
}

From source file:com.pluscubed.velociraptor.settings.SettingsActivity.java

private void showSupportDialog() {
    String content = getString(BuildConfig.FLAVOR.equals("play") ? R.string.support_dev_dialog
            : R.string.support_dev_dialog_notplay);
    if (PrefUtils.hasSupported(this) || !billingProcessor.listOwnedSubscriptions().isEmpty()) {
        content += "\n\n\uD83C\uDF89 " + getString(R.string.support_dev_dialog_badge) + " \uD83C\uDF89";
    }// ww  w .  j a  va 2s . c  o  m
    MaterialDialog.Builder builder = new MaterialDialog.Builder(this)
            .icon(Utils.getVectorDrawableCompat(this, R.drawable.ic_favorite_black_24dp))
            .title(R.string.support_development).content(Html.fromHtml(content));

    if (BuildConfig.FLAVOR.equals("play")) {
        if (!billingProcessor.isInitialized()) {
            Snackbar.make(findViewById(android.R.id.content), R.string.in_app_unavailable,
                    Snackbar.LENGTH_SHORT).show();
            return;
        }
        final List<SkuDetails> purchaseListingDetails = billingProcessor
                .getPurchaseListingDetails(new ArrayList<>(Arrays.asList(PURCHASES)));
        final List<SkuDetails> subscriptionListingDetails = billingProcessor
                .getSubscriptionListingDetails(new ArrayList<>(Arrays.asList(SUBSCRIPTIONS)));

        if (purchaseListingDetails == null || purchaseListingDetails.isEmpty()) {
            Snackbar.make(findViewById(android.R.id.content), R.string.in_app_unavailable,
                    Snackbar.LENGTH_SHORT).show();
            return;
        }

        purchaseListingDetails.addAll(0, subscriptionListingDetails);

        List<String> purchaseDisplay = new ArrayList<>();
        for (SkuDetails details : purchaseListingDetails) {
            NumberFormat format = NumberFormat.getCurrencyInstance();
            format.setCurrency(Currency.getInstance(details.currency));
            String amount = format.format(details.priceValue);
            if (details.isSubscription)
                amount = String.format(getString(R.string.per_month), amount);
            else {
                amount = String.format(getString(R.string.one_time), amount);
            }
            purchaseDisplay.add(amount);
        }

        builder.items(purchaseDisplay).itemsCallback(new MaterialDialog.ListCallback() {
            @Override
            public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                SkuDetails skuDetails = purchaseListingDetails.get(which);
                if (skuDetails.isSubscription) {
                    billingProcessor.subscribe(SettingsActivity.this, skuDetails.productId);
                } else {
                    billingProcessor.purchase(SettingsActivity.this, skuDetails.productId);
                }
            }
        });
    }

    if (BuildConfig.FLAVOR.equals("full")) {
        builder.positiveText(R.string.dismiss);
    }

    builder.show();
}

From source file:com.concursive.connect.web.modules.productcatalog.dao.Product.java

/**
 * Description of the Method//from w ww.  ja  v a2  s.  c  om
 *
 * @return Description of the Return Value
 */
public String toString() {
    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    Currency currency = Currency.getInstance("USD");
    formatter.setCurrency(currency);
    StringBuffer out = new StringBuffer();
    out.append("Product: " + this.getName() + "\r\n");
    out.append("Description: " + this.getPriceDescription() + "\r\n");
    if (sku != null) {
        out.append("Sku: " + this.getSku() + "\r\n");
    }
    out.append("Price: " + formatter.format(this.getTotalPrice()) + "\r\n");
    out.append("Configuration: " + this.getConfiguredSummary() + "\r\n");
    if (orderDescription != null) {
        out.append("Additional Information: " + this.getOrderDescription() + "\r\n");
    }
    out.append("\r\n");
    return out.toString();
}

From source file:com.pluscubed.velociraptor.SettingsActivity.java

private void showSupportDialog() {
    if (!billingProcessor.isInitialized()) {
        Snackbar.make(findViewById(android.R.id.content), R.string.in_app_unavailable, Snackbar.LENGTH_SHORT)
                .show();//  w w w .  ja  v  a  2  s  .  c o  m
        return;
    }

    final List<SkuDetails> purchaseListingDetails = billingProcessor
            .getPurchaseListingDetails(new ArrayList<>(Arrays.asList(PURCHASES)));
    final List<SkuDetails> subscriptionListingDetails = billingProcessor
            .getSubscriptionListingDetails(new ArrayList<>(Arrays.asList(SUBSCRIPTIONS)));

    if (purchaseListingDetails == null || purchaseListingDetails.isEmpty()) {
        Snackbar.make(findViewById(android.R.id.content), R.string.in_app_unavailable, Snackbar.LENGTH_SHORT)
                .show();
        return;
    }

    purchaseListingDetails.addAll(0, subscriptionListingDetails);

    List<String> purchaseDisplay = new ArrayList<>();
    for (SkuDetails details : purchaseListingDetails) {
        NumberFormat format = NumberFormat.getCurrencyInstance();
        format.setCurrency(Currency.getInstance(details.currency));
        String amount = format.format(details.priceValue);
        if (details.isSubscription)
            amount = String.format(getString(R.string.per_month), amount);
        else {
            amount = String.format(getString(R.string.one_time), amount);
        }
        purchaseDisplay.add(amount);
    }
    String content = getString(R.string.support_dev_dialog);
    if (PrefUtils.hasSupported(this) || !billingProcessor.listOwnedSubscriptions().isEmpty()) {
        content += "\n\n\uD83C\uDF89 " + getString(R.string.support_dev_dialog_badge) + " \uD83C\uDF89";
    }
    new MaterialDialog.Builder(this)
            .icon(Utils.getVectorDrawableCompat(this, R.drawable.ic_favorite_black_24dp))
            .title(R.string.support_development).content(content).items(purchaseDisplay)
            .itemsCallback(new MaterialDialog.ListCallback() {
                @Override
                public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                    SkuDetails skuDetails = purchaseListingDetails.get(which);
                    if (skuDetails.isSubscription) {
                        billingProcessor.subscribe(SettingsActivity.this, skuDetails.productId);
                    } else {
                        billingProcessor.purchase(SettingsActivity.this, skuDetails.productId);
                    }
                }
            }).show();
}

From source file:ro.expectations.expenses.ui.transactions.TransactionsAdapter.java

private void processTransfer(ViewHolder holder, int position) {
    mCursor.moveToPosition(position);// w  w w . ja v a2s  . co m

    // Set the account
    String fromAccount = mCursor.getString(TransactionsFragment.COLUMN_FROM_ACCOUNT_TITLE);
    String toAccount = mCursor.getString(TransactionsFragment.COLUMN_TO_ACCOUNT_TITLE);
    holder.mAccount.setText(mContext.getResources().getString(R.string.breadcrumbs, fromAccount, toAccount));

    // Set the amount
    NumberFormat format = NumberFormat.getCurrencyInstance();
    String fromCurrencyCode = mCursor.getString(TransactionsFragment.COLUMN_FROM_CURRENCY);
    String toCurrencyCode = mCursor.getString(TransactionsFragment.COLUMN_TO_CURRENCY);
    if (fromCurrencyCode.equals(toCurrencyCode)) {
        double amount = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_FROM_AMOUNT) / 100.0);
        Currency currency = Currency.getInstance(fromCurrencyCode);
        format.setCurrency(currency);
        format.setMaximumFractionDigits(currency.getDefaultFractionDigits());
        holder.mAmount.setText(format.format(amount));

        double fromBalance = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_FROM_BALANCE) / 100.0);
        String fromBalanceFormatted = format.format(fromBalance);
        double toBalance = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_TO_BALANCE) / 100.0);
        holder.mRunningBalance.setText(mContext.getResources().getString(R.string.breadcrumbs,
                fromBalanceFormatted, format.format(toBalance)));
    } else {
        Currency fromCurrency = Currency.getInstance(fromCurrencyCode);
        format.setCurrency(fromCurrency);
        format.setMaximumFractionDigits(fromCurrency.getDefaultFractionDigits());
        double fromAmount = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_FROM_AMOUNT) / 100.0);
        String fromAmountFormatted = format.format(fromAmount);
        double fromBalance = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_FROM_BALANCE) / 100.0);
        String fromBalanceFormatted = format.format(fromBalance);

        Currency toCurrency = Currency.getInstance(toCurrencyCode);
        format.setCurrency(toCurrency);
        format.setMaximumFractionDigits(toCurrency.getDefaultFractionDigits());
        double toAmount = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_TO_AMOUNT) / 100.0);
        double toBalance = NumberUtils
                .roundToTwoPlaces(mCursor.getLong(TransactionsFragment.COLUMN_TO_BALANCE) / 100.0);

        holder.mAmount.setText(mContext.getResources().getString(R.string.breadcrumbs, fromAmountFormatted,
                format.format(toAmount)));
        holder.mRunningBalance.setText(mContext.getResources().getString(R.string.breadcrumbs,
                fromBalanceFormatted, format.format(toBalance)));
    }

    // Set the color for the amount and the transaction type icon
    if (mSelectedAccountId == 0) {
        holder.mAmount.setTextColor(ContextCompat.getColor(mContext, R.color.colorOrange700));
        holder.mTypeIcon.setImageDrawable(
                DrawableHelper.tint(mContext, R.drawable.ic_swap_horiz_black_24dp, R.color.colorOrange700));
    } else {
        long fromAccountId = mCursor.getLong(TransactionsFragment.COLUMN_FROM_ACCOUNT_ID);
        long toAccountId = mCursor.getLong(TransactionsFragment.COLUMN_TO_ACCOUNT_ID);
        if (mSelectedAccountId == fromAccountId) {
            holder.mAmount.setTextColor(ContextCompat.getColor(mContext, R.color.colorRed700));
            holder.mTypeIcon.setImageDrawable(
                    DrawableHelper.tint(mContext, R.drawable.ic_call_made_black_24dp, R.color.colorRed700));
        } else if (mSelectedAccountId == toAccountId) {
            holder.mAmount.setTextColor(ContextCompat.getColor(mContext, R.color.colorGreen700));
            holder.mTypeIcon.setImageDrawable(DrawableHelper.tint(mContext,
                    R.drawable.ic_call_received_black_24dp, R.color.colorGreen700));
        }
    }
}

From source file:fr.hoteia.qalingo.core.web.util.impl.RequestUtilImpl.java

/**
 *
 *//*from   w  ww .ja v  a 2 s.c o m*/
public NumberFormat getNumberFormat(final RequestData requestData, final String currencyCode,
        final RoundingMode roundingMode, final int maximumFractionDigits, final int minimumFractionDigits,
        final int maximumIntegerDigits, final int minimumIntegerDigits) throws Exception {
    final Localization localization = requestData.getLocalization();
    final Locale locale = localization.getLocale();
    NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
    formatter.setGroupingUsed(true);
    formatter.setParseIntegerOnly(false);
    formatter.setRoundingMode(roundingMode);
    Currency currency = Currency.getInstance(currencyCode);
    formatter.setCurrency(currency);

    formatter.setMaximumFractionDigits(maximumFractionDigits);
    formatter.setMinimumFractionDigits(minimumFractionDigits);

    formatter.setMaximumIntegerDigits(maximumIntegerDigits);
    formatter.setMinimumIntegerDigits(minimumIntegerDigits);

    return formatter;
}

From source file:com.concursive.connect.web.modules.wiki.utils.WikiPDFUtils.java

public static String getFieldValue(WikiPDFContext context, CustomFormField field) {
    // Return output based on type
    switch (field.getType()) {
    case CustomFormField.TEXTAREA:
        return StringUtils.replace(field.getValue(), "^", CRLF);
    case CustomFormField.SELECT:
        return field.getValue();
    case CustomFormField.CHECKBOX:
        if ("true".equals(field.getValue())) {
            return "Yes";
        } else {/*from w  w  w  .  j a v  a  2  s . c o  m*/
            return "No";
        }
    case CustomFormField.CALENDAR:
        String calendarValue = field.getValue();
        if (StringUtils.hasText(calendarValue)) {
            try {
                String convertedDate = DateUtils.getUserToServerDateTimeString(null, DateFormat.SHORT,
                        DateFormat.LONG, field.getValue());
                Timestamp timestamp = DatabaseUtils.parseTimestamp(convertedDate);
                Locale locale = Locale.getDefault();
                int dateFormat = DateFormat.SHORT;
                SimpleDateFormat dateFormatter = (SimpleDateFormat) SimpleDateFormat.getDateInstance(dateFormat,
                        locale);
                calendarValue = dateFormatter.format(timestamp);
            } catch (Exception e) {
                LOG.error(e);
            }
        }
        return calendarValue;
    case CustomFormField.PERCENT:
        return field.getValue() + "%";
    case CustomFormField.INTEGER:
        // Determine the value to display in the field
        String integerValue = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(integerValue)) {
            try {
                NumberFormat formatter = NumberFormat.getInstance();
                integerValue = formatter.format(StringUtils.getIntegerNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not integer format: " + field.getValue());
            }
        }
        return integerValue;
    case CustomFormField.FLOAT:
        // Determine the value to display in the field
        String decimalValue = field.getValue();
        if (StringUtils.hasText(decimalValue)) {
            try {
                NumberFormat formatter = NumberFormat.getInstance();
                decimalValue = formatter.format(StringUtils.getDoubleNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not decimal format: " + field.getValue());
            }
        }
        return decimalValue;
    case CustomFormField.CURRENCY:
        // Use a currency for formatting
        String currencyCode = field.getValueCurrency();
        if (currencyCode == null) {
            currencyCode = field.getCurrency();
        }
        if (!StringUtils.hasText(currencyCode)) {
            currencyCode = "USD";
        }
        try {
            NumberFormat formatter = NumberFormat.getCurrencyInstance();
            if (currencyCode != null) {
                Currency currency = Currency.getInstance(currencyCode);
                formatter.setCurrency(currency);
            }
            return (formatter.format(StringUtils.getDoubleNumber(field.getValue())));
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
        return field.getValue();
    case CustomFormField.EMAIL:
        return field.getValue();
    case CustomFormField.PHONE:
        PhoneNumberBean phone = new PhoneNumberBean();
        phone.setNumber(field.getValue());
        PhoneNumberUtils.format(phone, Locale.getDefault());
        return phone.toString();
    case CustomFormField.URL:
        String value = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(value)) {
            if (!value.contains("://")) {
                value = "http://" + value;
            }
            if (value.contains("://")) {
                return value;
            }
        }
        return value;
    case CustomFormField.IMAGE:
        String image = field.getValue();
        if (StringUtils.hasText(image)) {
            return "WikiImage:" + image;
        }
        return image;
    default:
        return field.getValue();
    }
}

From source file:com.concursive.connect.web.modules.wiki.utils.WikiToHTMLUtils.java

public static String toHtml(CustomFormField field, Wiki wiki, String contextPath) {
    // Return output based on type
    switch (field.getType()) {
    case CustomFormField.TEXTAREA:
        String textAreaValue = StringUtils.replace(field.getValue(), "^", CRLF);
        return StringUtils.toHtml(textAreaValue);
    case CustomFormField.SELECT:
        return StringUtils.toHtml(field.getValue());
    case CustomFormField.CHECKBOX:
        if ("true".equals(field.getValue())) {
            return "Yes";
        } else {/* www. j  ava 2s  .c  om*/
            return "No";
        }
    case CustomFormField.CALENDAR:
        String calendarValue = field.getValue();
        if (StringUtils.hasText(calendarValue)) {
            try {
                String convertedDate = DateUtils.getUserToServerDateTimeString(null, DateFormat.SHORT,
                        DateFormat.LONG, field.getValue());
                Timestamp timestamp = DatabaseUtils.parseTimestamp(convertedDate);
                Locale locale = Locale.getDefault();
                int dateFormat = DateFormat.SHORT;
                SimpleDateFormat dateFormatter = (SimpleDateFormat) SimpleDateFormat.getDateInstance(dateFormat,
                        locale);
                calendarValue = dateFormatter.format(timestamp);
            } catch (Exception e) {
                LOG.error("toHtml calendar", e);
            }
        }
        return StringUtils.toHtml(calendarValue);
    case CustomFormField.PERCENT:
        return StringUtils.toHtml(field.getValue()) + "%";
    case CustomFormField.INTEGER:
        // Determine the value to display in the field
        String integerValue = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(integerValue)) {
            try {
                NumberFormat formatter = NumberFormat.getInstance();
                integerValue = formatter.format(StringUtils.getIntegerNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not integer format: " + field.getValue());
            }
        }
        return integerValue;
    case CustomFormField.FLOAT:
        // Determine the value to display in the field
        String decimalValue = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(decimalValue)) {
            try {
                NumberFormat formatter = NumberFormat.getInstance();
                decimalValue = formatter.format(StringUtils.getDoubleNumber(field.getValue()));
            } catch (Exception e) {
                LOG.warn("Could not decimal format: " + field.getValue());
            }
        }
        return decimalValue;
    case CustomFormField.CURRENCY:
        // Use a currency for formatting
        String currencyCode = field.getValueCurrency();
        if (currencyCode == null) {
            currencyCode = field.getCurrency();
        }
        if (!StringUtils.hasText(currencyCode)) {
            currencyCode = "USD";
        }
        try {
            NumberFormat formatter = NumberFormat.getCurrencyInstance();
            if (currencyCode != null) {
                Currency currency = Currency.getInstance(currencyCode);
                formatter.setCurrency(currency);
            }
            return (StringUtils.toHtml(formatter.format(StringUtils.getDoubleNumber(field.getValue()))));
        } catch (Exception e) {
            LOG.error("toHtml currency", e);
        }
        return StringUtils.toHtml(field.getValue());
    case CustomFormField.EMAIL:
        return StringUtils.toHtml(field.getValue());
    case CustomFormField.PHONE:
        PhoneNumberBean phone = new PhoneNumberBean();
        phone.setNumber(field.getValue());
        PhoneNumberUtils.format(phone, Locale.getDefault());
        return StringUtils.toHtml(phone.toString());
    case CustomFormField.URL:
        String value = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(value)) {
            if (!value.contains("://")) {
                value = "http://" + value;
            }
            if (value.contains("://")) {
                return ("<a href=\"" + StringUtils.toHtml(value) + "\">" + StringUtils.toHtml(value) + "</a>");
            }
        }
        return StringUtils.toHtml(value);
    case CustomFormField.IMAGE:
        String image = StringUtils.toHtmlValue(field.getValue());
        if (StringUtils.hasText(image)) {
            Project project = ProjectUtils.loadProject(wiki.getProjectId());
            return ("<img src=\"" + contextPath + "/show/" + project.getUniqueId() + "/wiki-image/" + image
                    + "\"/>");
        }
        return StringUtils.toHtml(image);
    default:
        return StringUtils.toHtml(field.getValue());
    }
}