Example usage for java.text DecimalFormatSymbols DecimalFormatSymbols

List of usage examples for java.text DecimalFormatSymbols DecimalFormatSymbols

Introduction

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

Prototype

public DecimalFormatSymbols() 

Source Link

Document

Create a DecimalFormatSymbols object for the default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:com.panet.imeta.core.util.StringUtil.java

public static double str2num(String pattern, String decimal, String grouping, String currency, String value)
        throws KettleValueException {
    // 0 : pattern
    // 1 : Decimal separator
    // 2 : Grouping separator
    // 3 : Currency symbol

    NumberFormat nf = NumberFormat.getInstance();
    DecimalFormat df = (DecimalFormat) nf;
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();

    if (!Const.isEmpty(pattern))
        df.applyPattern(pattern);/*from   www.j  av  a2s  . c om*/
    if (!Const.isEmpty(decimal))
        dfs.setDecimalSeparator(decimal.charAt(0));
    if (!Const.isEmpty(grouping))
        dfs.setGroupingSeparator(grouping.charAt(0));
    if (!Const.isEmpty(currency))
        dfs.setCurrencySymbol(currency);
    try {
        df.setDecimalFormatSymbols(dfs);
        return df.parse(value).doubleValue();
    } catch (Exception e) {
        String message = "Couldn't convert string to number " + e.toString();
        if (!isEmpty(pattern))
            message += " pattern=" + pattern;
        if (!isEmpty(decimal))
            message += " decimal=" + decimal;
        if (!isEmpty(grouping))
            message += " grouping=" + grouping.charAt(0);
        if (!isEmpty(currency))
            message += " currency=" + currency;
        throw new KettleValueException(message);
    }
}

From source file:com.greatmancode.craftconomy3.Common.java

/**
 * Format a balance to a readable string.
 *
 * @param worldName The world Name associated with this balance
 * @param currency  The currency instance associated with this balance.
 * @param balance   The balance./*from   ww w .  j a  v  a2s .  c o m*/
 * @param format    the display format to use
 * @return A pretty String showing the balance. Returns a empty string if currency is invalid.
 */
public String format(String worldName, Currency currency, double balance, DisplayFormat format) {
    StringBuilder string = new StringBuilder();

    if (worldName != null && !worldName.equals(WorldGroupsManager.DEFAULT_GROUP_NAME)) {
        // We put the world name if the conf is true
        string.append(worldName).append(": ");
    }
    if (currency != null) {
        // We removes some cents if it's something like 20.20381 it would set it
        // to 20.20

        String[] theAmount = BigDecimal.valueOf(balance).toPlainString().split("\\.");
        DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols();
        unusualSymbols.setGroupingSeparator(',');
        DecimalFormat decimalFormat = new DecimalFormat("###,###", unusualSymbols);
        String name = currency.getName();
        if (balance > 1.0 || balance < 1.0) {
            name = currency.getPlural();
        }
        String coin;
        if (theAmount.length == 2) {
            if (theAmount[1].length() >= 2) {
                coin = theAmount[1].substring(0, 2);
            } else {
                coin = theAmount[1] + "0";
            }
        } else {
            coin = "0";
        }
        String amount;
        try {
            amount = decimalFormat.format(Double.parseDouble(theAmount[0]));
        } catch (NumberFormatException e) {
            amount = theAmount[0];
        }

        // Do we seperate money and dollar or not?
        if (format == DisplayFormat.LONG) {
            String subName = currency.getMinor();
            if (Long.parseLong(coin) > 1) {
                subName = currency.getMinorPlural();
            }
            string.append(amount).append(" ").append(name).append(" ").append(coin).append(" ").append(subName);
        } else if (format == DisplayFormat.SMALL) {
            string.append(amount).append(".").append(coin).append(" ").append(name);
        } else if (format == DisplayFormat.SIGN) {
            string.append(currency.getSign()).append(amount).append(".").append(coin);
        } else if (format == DisplayFormat.MAJORONLY) {
            string.append(amount).append(" ").append(name);
        }
    }
    return string.toString();
}

From source file:org.openossad.util.core.util.StringUtil.java

public static double str2num(String pattern, String decimal, String grouping, String currency, String value)
        throws OpenDESIGNERValueException {
    // 0 : pattern
    // 1 : Decimal separator
    // 2 : Grouping separator
    // 3 : Currency symbol

    NumberFormat nf = NumberFormat.getInstance();
    DecimalFormat df = (DecimalFormat) nf;
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();

    if (!Const.isEmpty(pattern))
        df.applyPattern(pattern);//from   ww w.  j a  v a2  s.co m
    if (!Const.isEmpty(decimal))
        dfs.setDecimalSeparator(decimal.charAt(0));
    if (!Const.isEmpty(grouping))
        dfs.setGroupingSeparator(grouping.charAt(0));
    if (!Const.isEmpty(currency))
        dfs.setCurrencySymbol(currency);
    try {
        df.setDecimalFormatSymbols(dfs);
        return df.parse(value).doubleValue();
    } catch (Exception e) {
        String message = "Couldn't convert string to number " + e.toString();
        if (!isEmpty(pattern))
            message += " pattern=" + pattern;
        if (!isEmpty(decimal))
            message += " decimal=" + decimal;
        if (!isEmpty(grouping))
            message += " grouping=" + grouping.charAt(0);
        if (!isEmpty(currency))
            message += " currency=" + currency;
        throw new OpenDESIGNERValueException(message);
    }
}

From source file:de.langerhans.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, double dogeBtcConversion,
        final String userAgent, final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//ww w. java  2s  .c  om

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                final double btcRate = Double
                                        .parseDouble(Fiat.parseFiat(currencyCode, rate).toPlainString());
                                DecimalFormat df = new DecimalFormat("#.########");
                                df.setRoundingMode(RoundingMode.HALF_UP);
                                DecimalFormatSymbols dfs = new DecimalFormatSymbols();
                                dfs.setDecimalSeparator('.');
                                dfs.setGroupingSeparator(',');
                                df.setDecimalFormatSymbols(dfs);
                                final Fiat dogeRate = Fiat.parseFiat(currencyCode,
                                        df.format(btcRate * dogeBtcConversion));

                                if (dogeRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new com.dogecoin.dogecoinj.utils.ExchangeRate(dogeRate), source));
                                    break;
                                }
                            } catch (final NumberFormatException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:org.pentaho.di.core.util.StringUtil.java

public static double str2num(String pattern, String decimal, String grouping, String currency, String value)
        throws KettleValueException {
    // 0 : pattern
    // 1 : Decimal separator
    // 2 : Grouping separator
    // 3 : Currency symbol

    NumberFormat nf = NumberFormat.getInstance();
    DecimalFormat df = (DecimalFormat) nf;
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();

    if (!Const.isEmpty(pattern)) {
        df.applyPattern(pattern);// w  w w .j  av a  2  s . c  o m
    }
    if (!Const.isEmpty(decimal)) {
        dfs.setDecimalSeparator(decimal.charAt(0));
    }
    if (!Const.isEmpty(grouping)) {
        dfs.setGroupingSeparator(grouping.charAt(0));
    }
    if (!Const.isEmpty(currency)) {
        dfs.setCurrencySymbol(currency);
    }
    try {
        df.setDecimalFormatSymbols(dfs);
        return df.parse(value).doubleValue();
    } catch (Exception e) {
        String message = "Couldn't convert string to number " + e.toString();
        if (!isEmpty(pattern)) {
            message += " pattern=" + pattern;
        }
        if (!isEmpty(decimal)) {
            message += " decimal=" + decimal;
        }
        if (!isEmpty(grouping)) {
            message += " grouping=" + grouping.charAt(0);
        }
        if (!isEmpty(currency)) {
            message += " currency=" + currency;
        }
        throw new KettleValueException(message);
    }
}

From source file:nl.nn.adapterframework.parameters.Parameter.java

public void configure() throws ConfigurationException {
    if (StringUtils.isNotEmpty(getXpathExpression()) || StringUtils.isNotEmpty(styleSheetName)) {
        if (paramList != null) {
            paramList.configure();//from w ww . ja va 2 s. c o  m
        }
        String outputType = TYPE_XML.equalsIgnoreCase(getType()) || TYPE_NODE.equalsIgnoreCase(getType())
                || TYPE_DOMDOC.equalsIgnoreCase(getType()) ? "xml" : "text";
        boolean includeXmlDeclaration = false;

        transformerPool = TransformerPool.configureTransformer0("Parameter [" + getName() + "] ", classLoader,
                getNamespaceDefs(), getXpathExpression(), styleSheetName, outputType, includeXmlDeclaration,
                paramList, isXslt2());
    } else {
        if (paramList != null && StringUtils.isEmpty(getXpathExpression())) {
            throw new ConfigurationException("Parameter [" + getName()
                    + "] can only have parameters itself if a styleSheetName or xpathExpression is specified");
        }
    }
    if (isRemoveNamespaces()) {
        String removeNamespaces_xslt = XmlUtils.makeRemoveNamespacesXslt(true, false);
        try {
            transformerPoolRemoveNamespaces = new TransformerPool(removeNamespaces_xslt);
        } catch (TransformerConfigurationException te) {
            throw new ConfigurationException("Got error creating transformer from removeNamespaces", te);
        }
    }
    if (TYPE_DATE.equals(getType()) && StringUtils.isEmpty(getFormatString())) {
        setFormatString(TYPE_DATE_PATTERN);
    }
    if (TYPE_DATETIME.equals(getType()) && StringUtils.isEmpty(getFormatString())) {
        setFormatString(TYPE_DATETIME_PATTERN);
    }
    if (TYPE_TIMESTAMP.equals(getType()) && StringUtils.isEmpty(getFormatString())) {
        setFormatString(TYPE_TIMESTAMP_PATTERN);
    }
    if (TYPE_TIME.equals(getType()) && StringUtils.isEmpty(getFormatString())) {
        setFormatString(TYPE_TIME_PATTERN);
    }
    if (TYPE_NUMBER.equals(getType())) {
        decimalFormatSymbols = new DecimalFormatSymbols();
        if (StringUtils.isNotEmpty(getDecimalSeparator())) {
            decimalFormatSymbols.setDecimalSeparator(getDecimalSeparator().charAt(0));
        }
        if (StringUtils.isNotEmpty(getGroupingSeparator())) {
            decimalFormatSymbols.setGroupingSeparator(getGroupingSeparator().charAt(0));
        }
    }
    configured = true;

    if (getMinInclusive() != null || getMaxInclusive() != null) {
        if (!TYPE_NUMBER.equals(getType())) {
            throw new ConfigurationException(
                    "minInclusive and minInclusive only allowed in combination with type [" + TYPE_NUMBER
                            + "]");
        }
        if (getMinInclusive() != null) {
            DecimalFormat df = new DecimalFormat();
            df.setDecimalFormatSymbols(decimalFormatSymbols);
            try {
                minInclusive = df.parse(getMinInclusive());
            } catch (ParseException e) {
                throw new ConfigurationException(
                        "Attribute [minInclusive] could not parse result [" + getMinInclusive()
                                + "] to number decimalSeparator [" + decimalFormatSymbols.getDecimalSeparator()
                                + "] groupingSeparator [" + decimalFormatSymbols.getGroupingSeparator() + "]",
                        e);
            }
        }
        if (getMaxInclusive() != null) {
            DecimalFormat df = new DecimalFormat();
            df.setDecimalFormatSymbols(decimalFormatSymbols);
            try {
                maxInclusive = df.parse(getMaxInclusive());
            } catch (ParseException e) {
                throw new ConfigurationException(
                        "Attribute [maxInclusive] could not parse result [" + getMinInclusive()
                                + "] to number decimalSeparator [" + decimalFormatSymbols.getDecimalSeparator()
                                + "] groupingSeparator [" + decimalFormatSymbols.getGroupingSeparator() + "]",
                        e);
            }
        }
    }
}

From source file:org.fao.fenix.wds.core.utils.Wrapper.java

public DecimalFormat buildDecimalFormat(WrapperConfigurations c) {
    if (c != null) {
        StringBuilder pattern = new StringBuilder();
        pattern.append("#,###");
        if (c.getDecimalSeparator() != null) {
            if (c.getDecimalNumbers() > 0)
                pattern.append(".");
            for (int i = 0; i < c.getDecimalNumbers(); i++)
                pattern.append("0");
        }//  w w  w .ja v  a 2 s .co m
        DecimalFormatSymbols customSymbols = new DecimalFormatSymbols();
        customSymbols.setDecimalSeparator(c.getDecimalSeparator().charAt(0));
        customSymbols.setGroupingSeparator(c.getThousandSeparator().charAt(0));
        DecimalFormat df = new DecimalFormat(pattern.toString(), customSymbols);
        return df;
    } else {
        return new DecimalFormat("#,###.00");
    }
}

From source file:LPGoogleFunctions.LPGoogleFunctions.java

/**
 * The Google Maps Image APIs make it easy to embed a street view image into your image view.
 * @param location - The location (such as 40.457375,-80.009353).
 * @param imageWidth - Specifies width size of the image in pixels.
 * @param imageHeight - Specifies height size of the image in pixels.
 * @param heading - Indicates the compass heading of the camera. Accepted values are from 0 to 360 (both values indicating North, with 90 indicating East, and 180 South). 
 * If no heading is specified, a value will be calculated that directs the camera towards the specified location, from the point at which the closest photograph was taken.
 * @param fov - Determines the horizontal field of view of the image. The field of view is expressed in degrees, with a maximum allowed value of 120.
 * When dealing with a fixed-size viewport, as with a Street View image of a set size, field of view in essence represents zoom, with smaller numbers indicating a higher level of zoom.
 * @param pitch- Specifies the up or down angle of the camera relative to the Street View vehicle. This is often, but not always, flat horizontal.
 * Positive values angle the camera up (with 90 degrees indicating straight up).
 * Negative values angle the camera down (with -90 indicating straight down).
 * @param responseHandler//from  www  . j  a va  2s  . c om
 * @Override public void willLoadStreetViewImage();
 * @Override public void didLoadStreetViewImage(Bitmap bmp)
 * @Override public void errorLoadingStreetViewImage(Throwable error);
 */

public void loadStreetViewImageForLocation(LPLocation location, int imageWidth, int imageHeight, float heading,
        float fov, float pitch, final StreetViewImageListener responseHandler) {
    if (responseHandler != null)
        responseHandler.willLoadStreetViewImage();

    RequestParams parameters = new RequestParams();

    DecimalFormatSymbols separator = new DecimalFormatSymbols();
    separator.setDecimalSeparator('.');
    DecimalFormat coordinateDecimalFormat = new DecimalFormat("##.######");
    coordinateDecimalFormat.setDecimalFormatSymbols(separator);

    DecimalFormat twoDecimalFormat = new DecimalFormat(".##");
    twoDecimalFormat.setDecimalFormatSymbols(separator);

    parameters.put("key", this.googleAPIBrowserKey);
    parameters.put("sensor", sensor ? "true" : "false");
    parameters.put("size", String.format("%dx%d", imageWidth, imageHeight));
    if (location != null)
        parameters.put("location", String.format("%s,%s", coordinateDecimalFormat.format(location.latitude),
                coordinateDecimalFormat.format(location.longitude)));
    parameters.put("heading", twoDecimalFormat.format(heading));
    parameters.put("fov", twoDecimalFormat.format(fov));
    parameters.put("pitch", twoDecimalFormat.format(pitch));

    this.client.get(googleAPIStreetViewImageURL, parameters, new BinaryHttpResponseHandler() {
        @Override
        public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
            if (responseHandler != null)
                responseHandler.errorLoadingStreetViewImage(arg3);
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
            try {
                Bitmap bmp = BitmapFactory.decodeByteArray(arg2, 0, arg2.length);

                if (responseHandler != null)
                    responseHandler.didLoadStreetViewImage(bmp);
            } catch (Exception e) {
                e.printStackTrace();

                if (responseHandler != null)
                    responseHandler.errorLoadingStreetViewImage(e.getCause());
            }
        }
    });
}

From source file:ch.entwine.weblounge.common.content.ResourceUtils.java

/**
 * Returns the file size formatted in <tt>bytes</tt>, <tt>kilobytes</tt>,
 * <tt>megabytes</tt>, <tt>gigabytes</tt> and <tt>terabytes</tt>, where 1 kB
 * is equal to 1'000 bytes./*from  www . j  av  a2 s. co m*/
 * <p>
 * If no {@link NumberFormat} was provided,
 * <code>new DecimalFormat("0.#)</code> is used.
 * 
 * @param sizeInBytes
 *          the file size in bytes
 * @param format
 *          the number format
 * @return the file size formatted using appropriate units
 * @throws IllegalArgumentException
 *           if the file size is negative
 */
public static String formatFileSize(long sizeInBytes, NumberFormat format) throws IllegalArgumentException {
    if (sizeInBytes < 0)
        throw new IllegalArgumentException("File size cannot be negative");
    int unitSelector = 0;
    double size = sizeInBytes;

    // Calculate the size to display
    while (size >= 1000 && unitSelector < SIZE_UNITS.length) {
        size /= 1000.0d;
        unitSelector++;
    }

    // Create a number formatter, if none was provided
    if (format == null) {
        DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols();
        formatSymbols.setDecimalSeparator('.');
        format = new DecimalFormat("0.#", formatSymbols);
    }

    return format.format(size) + SIZE_UNITS[unitSelector];
}